Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment between union members

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.

like image 923
M.M Avatar asked Aug 05 '15 05:08

M.M


People also ask

How is a union declared?

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(.)

Can unions have functions?

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.

Can union have static members?

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.


1 Answers

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:

  1. The value computation of the right side reads u.f, which is the active member of the union. So everything is good.
  2. The assignment is executed. This involves writing the obtained result to u.i, which now changes the active member of the union.
like image 137
Daniel Jour Avatar answered Sep 28 '22 12:09

Daniel Jour