If I have an union
union U {
struct X x;
struct Y y;
struct Z z;
} u;
and both struct Y and struct Z have a struct X as the first field, then
can I always access u.x.<field> even if I am actually putting a struct Y
or Z in u?
Yes, for any practical implementation. But according to the
letter of the law (as I read it), no.
There is a special dispensation (6.5.2.3p5) for unions of
structs that share a "common initial sequence" of elements. If
`struct X' were `short shrift; double trouble; char broiled;' and
`struct Y' were `short shrift; double trouble; long john_silver;',
then you could access the `shrift' and `trouble' members of either,
no matter which had been most recently stored in the union.
*But* your union isn't like that. Your `struct Y' actually looks
like `struct X marks_the_spot; long john_silver;', and so does not
share a "common initial sequence" with `struct X'. X's first element
is a `short', Y's is a `struct X', `short' and `struct X' are not
compatible types, so there's no "common initial sequence."
You could regain compatibility by "expanding" the `struct X'
in `struct Y', listing its elements explicitly rather than lumping
them together as a `struct X' instance. That is, if `struct Y' were
`short snort; double down; long john_silver;' all would be well.
... as it almost certainly will be anyhow, on any practical
implementation. The objection I raise is an incredibly nit-picky,
angels-on-pinheads kind of argument that no practical programmer
would pay attention to -- until the optimizer bit his behind. And
it's possible I'm misinterpreting "corresponding members." This
may be a question for the kilobuck-an-hour language lawyers.