Local variable in C language (array) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Local variable in C language (array)

Can someone point me where does the C standard mandate that an Array like this one: int n[5] = { 4, 6, 8 }; which is a local to a Funtion (in this case, to MAIN), does initialize the element 4 with a value of 0( Zero )? I am asking because there is a challenge in C where the Question is: What outputs the program: Printf( โ€œ%d\nโ€, n[4] ); .... 1) 0 2) 6 3) 8 4) Error And seems that the right Answer is 1) 0 https://i.postimg.cc/Y96Pk5Q1/1-EEC9-B90-77-C8-49-F3-B62-E-E4-C7987310-B4.png

10th Jul 2019, 5:08 PM
Michael Buzgaru
Michael Buzgaru - avatar
4 Answers
+ 1
As stated by Ace according to this[1] thread, the initial value of any local variable with automatic storage duration class ( the ones being declared locally in a given function ) is undefined which means some random leftover value of the previous process that had taken up that particular region of memory. Also, as per ยง6.7.9 paragraph 10[2], " If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static or thread storage duration is not initialized explicitly, then: โ€” if it has pointer type, it is initialized to a null pointer; โ€” if it has arithmetic type, it is initialized to (positive or unsigned) zero; โ€” if it is an aggregate, every member is initialized (recursively) according to these rules, and any padding is initialized to zero bits; โ€” if it is a union, the first named member is initialized (recursively) according to these rules, and any padding is initialized to zero bits; " [1] https://stackoverflow.com/questions/1414215/initial-value-of-int-array-in-c [2] https://port70.net/~nsz/c/c11/n1570.html#6.7.9p10
10th Jul 2019, 5:48 PM
To Seek Glory in Battle is Glorious
To Seek Glory in Battle is Glorious - avatar
0
there are so many wrong C challenges :|
10th Jul 2019, 5:18 PM
Michael Buzgaru
Michael Buzgaru - avatar
0
Maybe someone can change 4) Error with 4) Undefined behavior and mark it as the right Answer.
10th Jul 2019, 6:13 PM
Michael Buzgaru
Michael Buzgaru - avatar
0
I just edited my Question with the question screenshot
10th Jul 2019, 6:21 PM
Michael Buzgaru
Michael Buzgaru - avatar