I have the following question: How are anonymous structures (or unions) properly initialized according to the current C1X draft? Is this legal:
struct foo {
int a;
struct {
int i;
int j;
};
int b;
};
struct foo f = { 1, 2, 3, 4 };
struct foo g = { 1, { 2 }, 3 };
In GCC, g.j == 0
and g.b == 3
, while in tcc g.j == 3
and g.b == 0
. The current draft says:
"[...] unnamed members of objects of structure and union type do not participate in initialization. Unnamed members of structure objects have indeterminate value even after initialization.".
Can this be really true? Isn't
struct foo h = { 0 };
supposed to set all members to 0?
Thanks very much!
UPDATE:
Since anonymous members seem to be only useful when mixing structs/unions, how to initialize this correctly:
struct bar {
int tag;
union {
double d;
int i;
};
};
? This gives errors in gcc < 4.6 and icc 11, but works in gcc 4.6, icc 12, clang and tcc:
struct bar a = { .tag = 1, .i = 42 };
This gives errors in clang and tcc, but works in gcc and icc:
struct bar b = { .tag = 1, { .i = 42 } };
Is the second one a violation of the standard?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…