This is often suggested, as a way to initialize a struct to zero values:
struct foo f = {0};
It is also mentioned that {}
could be used under gcc, but that this is not standard C99.
I wonder if this works for a struct whose layout may vary outside my control. I'm anxious because 0
is not a valid initializer for an array or struct. However gcc --std=c99
(gcc-8.1.1-1.fc28.x86_64) seems to accept {0}
even in such cases.
Question Does C99 accept {0}
as an initializer for any struct?
(Or a later C standard? Or contrawise, is there any reason not to rely on this? Are there compilers where {0}
could cause an error or a warning that would discourage its use?)
What I have tried
gcc warnings (enabled with -Wall
) suggest that this is some form of edge case in the standard, where gcc has been forced to accept 0
as an initializer for any type of struct field, but it will warn about it unless you are using the common {0}
idiom.
struct a { int i; };
struct b { struct a a; struct a a2; };
struct c { int i[1]; int j[1]; };
struct a a = {0}; /* no error */
struct b b = {0}; /* no error */
struct c c = {0}; /* no error */
/* warning (no error): missing braces around initializer [-Wmissing-braces] */
struct b b2 = {0, 0};
/* warning (no error): missing braces around initializer [-Wmissing-braces] */
struct c c2 = {0, 0};
struct a a2 = 0; /* error: invalid initializer */
int i[1] = 0; /* error: invalid initializer */