The value of uninitialized elements in an array of language C

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

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

The print result is 0. I tested it on the IAR and in the online compiler.

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

+8
c arrays initialization
source share
3 answers

Yes, standard C defines what happens in this case. Thus, no, there should not be a compiler compatible with the C standard, which in this case initializes with 0xFF .

Section 6.7.9 of the standard states:

Initialization

...

10 ... If an object that has a static or storage duration of threads is not initialized explicitly, then:

  • if it has a pointer type, it is initialized with a null pointer;
  • if it has an arithmetic type, it is initialized to (positive or unsigned) zero;
  • if it is a collection, each member is initialized (recursively) in accordance with these rules, and any padding is initialized with zero bits;
  • if it is a union, the first named element is initialized (recursively) in accordance with these rules, and any addition is performed with zero bits;

...

21 If the list enclosed in curly brackets contains fewer initializers than there are elements or elements of the population or fewer characters in the string literal used to initialize an array of known size than there are elements in the array, the rest of the population must be initialized implicitly in the same way as objects that have static storage duration.

+10
source share

From this post, it looks like this syntax will initialize all decimal places to zero. Moreover; all uninitialized data in the program data segment (in other words, all uninitialized global variables) is automatically set to zero, therefore, if you are looking for undefined behavior in this program, there is none; it will always be 0.

0
source share

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

0
source share

All Articles