0
//Language C
int main()
{
    int a[5]={0};
    for(int i=0 ; i < 4 ; i++ )
        printf("%d",a[i]);
    }
}

The output of the following was 1000 in gcc. But I thought it should print 1 and rest garbage values as I have not assigned values to other array locations.

If compiler version is not taken in account, is my thinking right? Or I am missing something.

prasoon
  • 11
  • 2

1 Answers1

3

The C standard (citing the latest C11 draft N1570 here) explains this quite well.

§6.7.9 Initialization, p21:

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

(emphasis mine)

so, every element except a[0] in your code is initialized implicitly. Now let's look what that means:

§6.7.9 Initialization, p10:

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;

(again, emphasis mine)

so, a[1] to a[4] are initialized to 0 -- type int is an arithmetic type.

  • Thanks for giving clarity. – prasoon Apr 21 '18 at 17:50
  • @prasoon you're welcome. The C standard can be a bit hard to read at first, but it's the one **definitive** reference :) Btw, if your assumption would have been correct, your program would have been "undefined" -- you're not allowed to use uninitialized values and your program is free to do "whatever" if you do ... –  Apr 21 '18 at 17:55
  • I will try to read C standard though the use so many standard terms makes it so complex. Thanks once again. – prasoon Apr 21 '18 at 18:01