07-27-2023, 11:45 AM
Why does following example not 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, t.x.x, t.y.y);
Test t2 = { 2, y }; // ERROR
printf("2: %d %d '%s'\n", t2.pos, t2.x.x, t2.y.y);
Test t3 = { 3 }; // OK
printf("3: %d %d '%s'\n", t3.pos, t3.x.x, t3.y.y);
return 0;
}
> main.c: In function ‘main’:<br>
> main.c:25:3: error: incompatible types when initializing type ‘int’ using type ‘Y’<br>
> Test t2 = { 2, y }; // ERROR<br>
> ^
EDIT:
By the way: `t2.y = y;` works
#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, t.x.x, t.y.y);
Test t2 = { 2, y }; // ERROR
printf("2: %d %d '%s'\n", t2.pos, t2.x.x, t2.y.y);
Test t3 = { 3 }; // OK
printf("3: %d %d '%s'\n", t3.pos, t3.x.x, t3.y.y);
return 0;
}
> main.c: In function ‘main’:<br>
> main.c:25:3: error: incompatible types when initializing type ‘int’ using type ‘Y’<br>
> Test t2 = { 2, y }; // ERROR<br>
> ^
EDIT:
By the way: `t2.y = y;` works