From the standard:
In a union, at most one of the non-static data members can be active at any time, that is, the value of at most one of the non-static data members can be stored in a union at any time. [ Note: One special guarantee is made in order to simplify the use of unions: If a standard-layout union contains several standard-layout structs that share a common initial sequence (9.2), and if an object of this standard-layout union type contains one of the standard-layout structs, it is permitted to inspect the common initial sequence of any of standard-layout struct members; see 9.2. — end note ]
Seems to me that the special guarantee indicates that
struct PointXYZ {
union {
struct {
double xyz[3];
};
struct {
double x, y, z;
};
};
};
should work just fine when reading the member that was not last written (See it happen).
Note, however, that according to the specs, your example of
struct PointXYZ {
union {
struct {
double xyz[3];
};
double x, y, z;
};
};
is undefined behaviour when reading the member that was not last written (See it happen). When setting xyz[0]
, xyz[1]
and xyz[2]
, all of x
, y
and z
have the same value as xyz[0]
in the linked example. I would expect most compilers to behave like this, but the standard does not guarantee it.