2

If we define an array/struct like this:

int a[5] = { 1, 2, 3, };
struct b { int c; int d; } e = { 1, };

or even:

int a[5] = { 1, 2, 3 };
struct b { int c; int d; } e = { 1 };

we get no error from C compiler as the missing elements are initialized with a 0 default, like when we write explicitly:

int a[5] = { 1, 2, 3, 0, 0 };
struct b { int c; int d; } e = { 1, 0 };

Is there a way to disable the default initialization of an array in C, so that the compiler gives an error or warning when the elements are not all defined?

I am using gcc 4.8.0 (MinGW).

11
  • 3
    For the field initializers, you can use -Wmissing-field-initializers warning, and you can turn it into an error using -Werror. Commented May 21, 2020 at 10:31
  • @BillyJoe I misunderstood the question. I thought you wanted to force the remaining elements to be indeterminate instead of initialized to zero. Commented May 21, 2020 at 10:35
  • 1
    @JorgeBellon That's the answer. You should put it in a proper answer. Commented May 21, 2020 at 10:35
  • 1
    And unfortunately there's no equivalent for arrays, so struct {int a,b;} struc_array[5] = { {5,0} }; will not result in errors despite the missing initializers for indices 1..4 of the array of structs. That is, the structs at indices 1..4 will be default-initialized, even with -Wmissing-field-initializers. Commented May 21, 2020 at 10:36
  • OK, I started asking about arrays, but I was actually interested in structs, so the -Wmissing-field-initializers actually satisfy my needs and answers half of the question. We can answer the other half saying that there is no equivalent then. Commented May 21, 2020 at 10:39

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.