Search code examples
cc99unionscompound-literals

Is it possible (legal) to assign an anonymous union in a compound literal?


I have a struct:

typedef struct _n
{
    int type;
    union {
        char *s;
        int i;
    };
} n;

When I try to assign a compound literal, like:

node n1 = {1, 0};
node n2 = {2, "test"};

gcc gives me some warnings such as:

warning: initialization makes pointer from integer without a cast
warning: initialization from incompatible pointer type

Well, it's clear that the compiler isn't sure about me just assigning a value to a possibly ambiguous type. However, even if I try to specify more precisely:

node n0 = {type: 1, i: 4};

I get:

error: unknown field ‘i’ specified in initializer

I have read that if I put (union <union name>) before i: then it may work. However, I prefer having an anonymous union. Is there a way to do it?


Solution

  • Anonymous unions are not standard C -- they are a compiler extension. I would strongly recommend giving the union a name. If you insist on using an anonymous union, then you can only give an initializer for the first element of it:

    node n0 = {1, 0};  // initializes `s' to 0
    

    When compiled with -Wall -Wextra -pedantic, gcc gave me the warning "missing braces around initializer", which is a valid warning. The initializer should actually be specified like this:

    node n0 = {1, {0}};  // initializes `s' to 0
    

    Now this only gives a warning that "ISO C doesn't support unnamed structs/unions".

    If you give the union a name, then you can use a C99 feature called designated initializers to initialize a specific member of the union:

    typedef struct
    {
        int type;
        union {
            char *s;
            int i;
        } value;
    } node;
    
    node n0 = {1, { .s = "string" }};
    node n1 = {2, { .i = 123 }};
    

    You need the union to have a name; otherwise, the compiler will complain about the designated initializer inside it.

    The syntax you were trying to use node n0 = {type: 1, i: 4} is invalid syntax; it looks like you were trying to use designated initializers.