Search code examples
cstandardsc99c89ansi-c

C90 compound literals


In C99, if x was declared earlier and is of type v2, then I can write:

x = (v2) { 1, 2 };

where v2 is:

typedef struct {
    int x;
    int y;
} v2;

Can I do something similar in C90?


Solution

  • AFAIK, compound literals were introduced exactly in C99. However, if you're using GCC, this feature is available as an extension. Quoting GCC docs:

    ISO C99 supports compound literals. A compound literal looks like a cast containing an initializer. Its value is an object of the type specified in the cast, containing the elements specified in the initializer; it is an lvalue. As an extension, GCC supports compound literals in C90 mode and in C++.

    Another note regarding this feature of GCC:

    As a GNU extension, GCC allows initialization of objects with static storage duration by compound literals (which is not possible in ISO C99, because the initializer is not a constant). It is handled as if the object was initialized only with the bracket enclosed list if the types of the compound literal and the object match. The initializer list of the compound literal must be constant. If the object being initialized has array type of unknown size, the size is determined by compound literal size.

    static struct foo x = (struct foo) {1, 'a', 'b'};
    static int y[] = (int []) {1, 2, 3};
    static int z[] = (int [3]) {1};
    

    The above lines are equivalent to the following:

    static struct foo x = {1, 'a', 'b'};
    static int y[] = {1, 2, 3};
    static int z[] = {1, 0, 0};