10

I have an array of 3 elements. But I only want to initialize 2 of them. I let the third element blank.

unsigned char array[3] = {1,2,};
int main(){
  printf("%d",array[2]);
    return 0;
}

The print result is 0. I tested it on IAR, and some online compiler.

Is there any C rule for the value of third element? Is there any compiler filling the third element by 0xFF ? (Especially cross compiler)

sepp2k
  • 363,768
  • 54
  • 674
  • 675
Ngo Thanh Nhan
  • 503
  • 2
  • 5
  • 17

3 Answers3

11

Yes, the C standard does define what happens in this case. So no, there should be no C standard compliant compiler that intialises with 0xFF in this case.

Section 6.7.9 of the standard says:

Initialisation

...

10 ...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;

...

21 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.

kaylum
  • 13,833
  • 2
  • 22
  • 31
0

From this post, it appears that that syntax will initialize all elements after the comma to zero. Moreover; all uninitialized data in the data segment of the program (in other words all uninitialized global variables) are automatically set to zero, so if you are looking for undefined behavior in this program, there isn't any; it will always be 0.

Community
  • 1
  • 1
Joshua Rahm
  • 534
  • 2
  • 5
0

This can be achieved with gcc extension as below unsigned char array[10] = {1,2,[2 ... 9] = 0xFF};

  • 2
    That doesn't actually answer the question. OP wanted to know if there is a rule for what value unspecified indices are initialised with (there is) and would any compiler implicitly initialise them to 0xFF (no standards compliant compiler would do so). – Iskar Jarak Sep 22 '15 at 04:27