21

Since C99 (and C++20), it's possible to initialize structs using this syntax:

struct info
{
    char    name[8+1];
    int     sz;
    int     typ;
};

struct info  arr[] =
{
    [0] = { .sz = 20, .name = "abc" },
    [9] = { .sz = -1, .name = "" }
};

What happens to the unspecified fields?

Jorengarenar
  • 2,705
  • 5
  • 23
  • 60
Matt Joiner
  • 112,946
  • 110
  • 377
  • 526
  • 2
    I'm pretty sure that they are 0 initialised. But I'm also sure that someone else will be faster to find the portion of the C99 spec that makes it so. ... And I was right! – torak Jul 30 '10 at 18:45

1 Answers1

33

They are zeroed. From the C99 standard §6.7.8 (Initialization)/21,

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • Exactly what I wanted to know, complete with standard quote. Thanks! – Matt Joiner Jul 30 '10 at 18:49
  • 3
    @Matt Joiner: Was there ever any doubt? Oh, and for completeness see §6.7.8 (Initialization)/10, which effectively states that such static storage is NULL/0 initialized. – torak Jul 30 '10 at 18:52
  • 2
    A useful consequence of this fact is that `{ 0 }` is a universal zero-initializer which can be used for any aggregate type (and actually any type at all, IIRC, though some compilers might give warnings if it's used for simple types). – R.. GitHub STOP HELPING ICE Jul 30 '10 at 23:30
  • @torak I think static duration float point is initialized to +0,thus the original sentence in C99 §6.7.8 is "if it has `arithmetic type`, it is initialized to `(positive or unsigned) zero`;", maybe I am a little pedantic:)? – Allan Ruin May 28 '12 at 07:53