2

Consider the following C code:

typedef struct abc {
  int a[4];
  int b;
  int c;
} abc_t;

abc_t x = { 0 };

I have found that comping this with gcc -c -Wall -Wextra -pedantic -std=c99 does not generate any warning or error messages. My interpretation is that the 0 would denote the initializer for the member a. But a is an array, not a scalar. If I replace the 0 with 1 this immediately yields the expected warning messages:

warning: missing braces around initializer [-Wmissing-braces]
   14 | abc_t x = { 1 };
      |           ^
      |             { }

Is there some exception in the C standard that { 0 } is alwaysinterpreted as the initializer which sets everything to zero? Common sources of documentation do not seem to discuss the apparent mismatch of the type (array vs. scalar).

I am aware that initializers must not be empty, i.e. { } is not a valid initializer.

Sven
  • 1,364
  • 2
  • 17
  • 19

1 Answers1

2

Why is {0} always a valid struct initializer?

Because the syntax allows it. It allows to omit braces for initializing sub-aggregates.

Is there some exception in the C standard that { 0 } is always interpreted as the initializer which sets everything to zero?

No, there's no difference. Any variables at file scope without explicit initializes are always initialized to zero or pointer to NULL. For reference see cppreference initialization.

The only difference is the presence of the warning and the value of first array element. In case of = {0} the first array element will be explicitly initialized to zero and the rest of the array elements and rest of struct members are implicitly initialized to zero.

In case of = {1} the first array element will be explicitly initialized to one. And the rest of the array elements and the rest of struct member are implicitly initialized to zero. Och, and your compiler happens to issue a warning also, which is "quality of implementation" thing.

The = {0} being a common code where programmers don't care if braces check out or not, so your compiler being a good quality compiler doesn't want to bother programmer that they forgot about braces in such cases. If you would want your compiler to issue a warning in such case, you know the answer - fund your compiler development, create a feature request and/or contribute to the community and implement a new like -Wmissing-braces-also-when-zero warning.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • `= {0}` is the ideomatic way to express: "Please zero initialize this object." We would leave the braces empty if we could, but unfortunately `= {}` is not legal C code, so the `0` must be added. – cmaster - reinstate monica Aug 14 '20 at 08:04
  • 1
    I believe this answer misses the whole point of the question. I did not write `{{0}}` which would initialize the array inside the struct. But I wrote `{0}` instead. – Sven Aug 14 '20 at 09:39