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
source share