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).

BillyJoe
  • 878
  • 7
  • 25
  • 3
    For the field initializers, you can use `-Wmissing-field-initializers` warning, and you can turn it into an error using `-Werror`. – Jorge Bellon May 21 '20 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. – klutt May 21 '20 at 10:35
  • 1
    @JorgeBellon That's the answer. You should put it in a proper answer. – klutt May 21 '20 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`. – MemReflect May 21 '20 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. – BillyJoe May 21 '20 at 10:39
  • @JorgeBellon While this is excellent for structs, it won´t work for arrays: https://godbolt.org/z/nUm24o – RobertS supports Monica Cellio May 21 '20 at 10:39
  • @klutt I modified again the question title because like this it is more complete and corresponds to what actually I am looking for. – BillyJoe May 21 '20 at 10:45
  • @JorgeBellon If you want to make an answer with your comment, supposing as other have said that there is no equivalent for arrays, otherwise I will answer it myself. – BillyJoe May 21 '20 at 10:46
  • I didn't post it as an answer because it didn't answer the whole question, but now it seems this has been already asked before. Maybe close as duplicate. – Jorge Bellon May 21 '20 at 11:04
  • What about `int a[] = { 1, 2, 3, };` with `static_assert(sizeof(a)/sizeof(*a) == 5)`? It will not detect `int a[] = { [4] = 1, };` but still. – KamilCuk May 21 '20 at 11:12
  • @Mike Kinghan yes, I think that answeres my question. I searched before but I didn't find it. – BillyJoe May 21 '20 at 11:18

0 Answers0