Is this code well-defined?
int main()
{
union
{
int i;
float f;
} u;
u.f = 5.0;
u.i = u.f; // ?????
}
It accesses two different union members in one expression so I am wondering if it falls foul of the [class.union]/1 provisions about active member of a union.
The C++ Standard seems to underspecify which operations change the active member for builtin types, and what happens if an inactive member is read or written.
Syntax for declaring a union is same as that of declaring a structure except the keyword struct. Note : Size of the union is the the size of its largest field because sufficient number of bytes must be reserved to store the largest sized field. To access the fields of a union, use dot(.)
A union can have member functions (including constructors and destructors), but not virtual functions. A union cannot have base classes and cannot be used as a base class.
In C++ union can contain static members which, as in the case of classes, belong to a class and therefore are common to all objects.
The assignment operator (=) and the compound assignment operators all group right-to-left. [...] In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression. [...]
[N4431 §5.18/1]
Under the premise that in your case the value computation of the left hand side (involving merely a member access, not a read) does not cause undefined behaviour, I'd apply the above as follows:
u.f
, which is the active member of the union. So everything is good.u.i
, which now changes the active member of the union.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With