26

In the C code I am analyzing, there are a lot of multidimensional (struct) arrays which are initialized with a different number of curly brackets e.g. {{0}} or {{{0}}}.

However, replacing these by {0} also works perfectly.

Is there a (functional) difference between using one or more sets of curly brackets ({}) occurrences ?

Draken
  • 3,134
  • 13
  • 34
  • 54
Michel Keijzers
  • 15,025
  • 28
  • 93
  • 119
  • 4
    [Initializing entire 2D array with one value](http://stackoverflow.com/questions/15520880/initializing-entire-2d-array-with-one-value) should answer why `{0}` works. – Lundin Nov 14 '16 at 14:46

3 Answers3

15

No, there is no functional difference. The C standard allows to leave out intermediate {}. In particular, the form { 0 } is an initializer that can be used for all data types.

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177
8

You have two choices: either { 0 }, which works for any aggregate or union type and zero initializes every member, or using the correct form which must correspond to all members correctly.

2501
  • 25,460
  • 4
  • 47
  • 87
4

Just to reiterate what Jens has already said, {0} works for any type. It is the "universal zero initializer" in C. See C11 draft, 6.7.9 Initialization.

So, to initialize a 3D array either {0} or {{{0}}} can be used. Personally I'd use {0} as it's easier to type and read and works for every type. That means, the following are all valid initializations:

int main(void)
{
    int x = {0,};
    int *p = {0,};
    int *q = {0};
    int arr[3][3][3][3] = {0};
}

More importantly, if you happen to have some unknown/opaque type, for example from a third-party libraries, then the only portable way to initialize them is using {0}. Any other way of zero-ing it (such as using memset() or directly some_type_t state = 0;) would require some internal knowledge of the type involved and risks being non-portable.

P.P
  • 117,907
  • 20
  • 175
  • 238
  • 3
    If you have an opaque type from another library, you shouldn't meddle with its internals in the first place, but let that library initialize it. – Lundin Nov 14 '16 at 14:51