Look at this code:
struct A {
short s;
int i;
};
struct B {
short s;
int i;
};
union U {
A a;
B b;
};
int fn() {
U u;
u.a.i = 1;
return u.b.i;
}
Is it guaranteed that fn()
returns 1
?
Note: this is a follow-up question to this.
Yes, this is defined behavior. First lets see what the standard has to say about
A
andB
. [class.prop]/3 hasSo
A
andB
are both standard layout types. If we look at [class.mem]/23and [class.mem]/22
and [class.mem]/25
Then we have that the classes have the same common initial sequence, are laid out the same, and accessing the same member of the non-active type is treated as if accessing that member of the active type.