+ 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
6 ответов
+ 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
0
there are so many wrong C challenges :|
0
Maybe someone can change 4) Error with 4) Undefined behavior and mark it as the right Answer.
0
I just edited my Question with the question screenshot