Anonymous union in initializer

Why doesn't the following example work in C?

#include <stdio.h> typedef struct { int x; } X; typedef struct { char y[10]; } Y; typedef struct { int pos; union { X x; Y y; }; } Test; int main() { X x = { 65 }; Y y = { "Hallo" }; Test t = { 1, x }; // OK printf("1: %d %d '%s'\n", t.pos, txx, tyy); Test t2 = { 2, y }; // ERROR printf("2: %d %d '%s'\n", t2.pos, t2.xx, t2.yy); Test t3 = { 3 }; // OK printf("3: %d %d '%s'\n", t3.pos, t3.xx, t3.yy); return 0; } 

main.c: In the function 'main:
main.c: 25: 3: error: incompatible types when initializing the type "int using type" Y
Testing t2 = {2, y}; // ERROR
^

EDIT: By the way: t2.y = y; works

+6
source share
2 answers

Since the type of initializer is not parsed and does not match against possible union members.

Instead, you just have to provide an initializer for the first member of union .

Draft C11 ยง6.7.9.17:

Each initializer list, enclosed in braces, has a current object associated with it. When there is no designation, the subobjects of the current object are initialized in the order corresponding to the type of the current object: array elements in ascending index order, structure members in the declaration order, and the first named member of the union.

As already mentioned, you can use pointers to control this:

 Test t2 = { 2, .y = y }; 

should work (which .y is the designation "new" on C99).

+4
source

You must indicate that you are initializing an element other than the first:

  Test t2 = { 2, { .y = y } } ; 

Otherwise, the compiler will try to initialize it as if you wrote: .x = y

+2
source

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


All Articles