Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array initialization using {0} fails except for first element in some compilers [duplicate]

Tags:

c++

c

Possible Duplicate:
C and C++ : Partial initialization of automatic structure

For a long time I have been using

char array[100] = {0};

to initialize all the elements of the array to 0. However, I recently stumbled on a compiler (Code Composer Studio by Texas Instruments) where this didn't work. The statement had the effect of initializing only the first element to 0.

Could this behavior be a C vs C++ difference, a compiler difference, or is this a bug in the implementation?

like image 850
Gustavo Litovsky Avatar asked Nov 30 '22 04:11

Gustavo Litovsky


2 Answers

It's just a bug. In both C and C++, array should be filled with zeroes.


Since this is a small answer, might as well go overboard:

C++11 §8.5.1/7:

If there are fewer initializer-clauses in the list than there are members in the aggregate, then each member not explicitly initialized shall be initialized from an empty initializer list (8.5.4). [Example:
struct S { int a; const char* b; int c; };
S ss = { 1, "asdf" };
initializes ss.a with 1, ss.b with "asdf", and ss.c with the value of an expression of the form int(), that is, 0. —end example ]

C99 §6.7.8/21 (sorry, don't have C11 off-hand):

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.

like image 188
GManNickG Avatar answered Dec 02 '22 17:12

GManNickG


In C, there is no partial initialization (see 6.7.9/19 in the C11 Standard). An object either is fully initialized (all its bytes) or is completely uninitialized.

Your compiler is not C-conformant.

The initialization shall occur in initializer list order, each initializer provided for a particular subobject overriding any previously listed initializer for the same subobject; all subobjects that are not initialized explicitly shall be initialized implicitly the same as objects that have static storage duration.

like image 26
pmg Avatar answered Dec 02 '22 18:12

pmg