Member initialization issue

I am trying to make the code below:

typedef union Data
{
   int i;
}data;

int main( )
{
   data d1;     
   d1.i = 10; // OK
   data d3 = {7};// OK
   data d2.i = 20; // Gives error
}

My question is, why does it give an error for data d2.i = 20and work for others?

+4
source share
1 answer

Because this is not valid syntax.

He has nothing to do with union, that is, he will be the same for struct.

You are trying to use a member unionname as a name that is not valid. Names cannot contain a period ( .).

Initializations work because there is a mapping (view) of the initializer expression (right side) to the type of the left side, but this is not what you are trying to use on the last line.

I think this will work, and seems to be close:

data d2 = { .i = 20 };

C99 .

+6

Source: https://habr.com/ru/post/1655459/


All Articles