Is it possible (legal) to designate an anonymous union in a composite literal?

I have a structure:

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

When I try to assign a composite literal, for example:

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 is not sure that I am just assigning a value, possibly to an ambiguous type. However, even if I try to clarify:

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

I get:

error: unknown field β€˜i’ specified in initializer

I read that if I put (union <union name>)up i:, then it can work. However, I prefer to have an anonymous union. Is there any way to do this?

+5
source share
1 answer

C - . . , :

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

-Wall -Wextra -pedantic, gcc " ", . :

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

, "ISO C /".

, C99, , :

typedef struct
{
    int type;
    union {
        char *s;
        int i;
    } value;
} node;

node n0 = {1, { .s = "string"; }};
node n1 = {2, { .i = 123; }};

, ; .

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

+7

All Articles