Reputation: 27632
does this code initialize all the elements of the array in all major C and C++ compilers or not?
int arr[100] = {0};
Upvotes: 3
Views: 271
Reputation: 9972
If the array happens to be an array of structs, you'll quickly run into problems. Heck, you can't even do a single struct.
This simple example shows that two major compilers (gcc and msvc) do not follow the specifications as quoted in ouah's answer (gcc seemingly, from its warning, and msvc from its error msg).
Consider this source, foo.c / foo.cpp:
void foo(void) {
struct A {
int i;
int j;
};
struct A single = {0};
}
Compile, with both gcc and g++:
$ gcc -Wall -W -c foo.c
foo.c: In function 'foo':
foo.c:6:14: warning: missing initializer
foo.c:6:14: warning: (near initialization for 'single.j')
$ g++ -Wall -W -c foo.cpp
foo.cpp: In function 'void foo()':
foo.cpp:6:27: warning: missing initializer for member 'foo()::A::j'
The same warnings are given for arrays. This gcc is only two years old: gcc --version
--> gcc (GCC) 4.5.3
.
Plain {}
without the 0 works fine in gcc, including for arrays. And you could always compile with -w
(lower case) to disable all warnings.
But MSVS 2012 has the equal and opposite problem with this example (including arrays).
It likes {0},
and treats {}
as an error :
Error C2059: syntax error : '}'
Upvotes: 1
Reputation: 145899
In all compilers. This is guaranteed by the C Standard and the C++ Standard.
For example, for C here is the relevant paragraph:
(C99, 6.7.8p21) "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."
and
(C99, 6.7.8p10) "If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then: [...] if it has arithmetic type, it is initialized to (positive or unsigned) zero; [...]"
Upvotes: 6