[Solved] Creating an initializer list in C [closed]


struct S
{
    int a, d, p;
};

#define S_INITIALIZER { 12, 10, 77 }

struct S s = S_INITIALIZER;

You (typically) provide a value for each member. If you provide less, the remaining members are zero-initialized (C99, 6.7.8.21). If you provide more, you will get a compiler warning and the additional initializer values are discarded.

Edit: As Olaf pointed out (thanks!), it is better to use designated initializers:

#define S_INITIALIZER { .a = 12, .d = 10, .p = 77 }

This way, the initializer is robust against changes of the struct associated with:

struct S
{
    int d, a, o, p;
    //        ^ new value; a and d inverted!
};

is still initialized as before, o is initialized to 0 (C99 6.7.8.19). And if you now drop p, you get a compile error – at least with gcc.

Actually, the standard states:

If a designator has the form
   . identifier
then the current object (defined below) shall have structure or union type and the
identifier shall be the name of a member of that type.

(C99 6.7.8.7). However, did not find what happens if not doing so.

Similarly:

No initializer shall attempt to provide a value for an object not contained within the entity being initialized.

(C99 6.7.8.2), again no word if doing otherwise (providing more elements). Discarding additional elements seems to be legal, not compiling does not seem to be illegal either…

7

solved Creating an initializer list in C [closed]