union
overlays all the listed members on top of each other (although some may extend farther than the overlapping initial sections), so assigning to either .a
or .b
is writing over the same part of memory. With that in mind, the output should make sense.
You probably were thinking of struct
's behavior if you were expecting an output of 10.
In really twisted scenarios, it's possible to have parts of different values stored in a union simultaneously, but generally the partially overwritten values will be assumed corrupt. For example, this:
union {
char a;
struct { char ba; char bb; } b;
} s;
can store s.a
and s.b.bb
at the same time, but since s.a
overlaps s.b.ba
, assigning to s.a
stomps on s.b.ba
, and by implication all of s.b
is no longer trustworthy.
Often unions intended to store different types will be embedded in a struct whose first member records which union member is in use:
struct {
int type;
union {
char ch;
int n;
} datum;
} atom;
Here, type
probably would contain an enumerated value to indicate whether datum.ch
or datum.n
was in use in the atom.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…