4

I have a faint memory of reading that code like int x[4] = {}; used to initialize a struct/array to default values is relying on a non standard (but widespread) extension that first appeared in gcc, and the correct version (as apparently stated in the standard) is int x[4] = { 0 };

Is this correct?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
user10607
  • 3,011
  • 4
  • 24
  • 31

1 Answers1

7

In C the initializer list is defined the following way

initializer:
assignment-expression
{ initializer-list }
{ initializer-list , }

While in C++ it is defined the following way

braced-init-list:
{ initializer-list ,opt }
{ }

As you can see C++ allows an empty brace-init list while in C initializer list may not be omitted.

So you may write in C++

int x[4] = {}; 

However in C this definition does not satisfies the Standard (though it can be an implementation-defined language extension). So you have to write

int x[4] = { 0 };

In the both cases elements of the array will be zero-initialized.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • As an additional note, a literal zero is a valid initialization constant for all types, and represents the value used by default initialization of static objects. So `static T foo = {0};` will initialize `foo` to the same value as `static T foo`, and within a function `T bar = {0};` will initialize `bar` to the same value as `foo` had been initialized. – supercat Oct 22 '18 at 16:29