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?
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" };
initializesss.a
with1
,ss.b
with"asdf"
, andss.c
with the value of an expression of the formint()
, 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With