C++ 14 - union - Is it legal to access inactive member?

108 Views Asked by At

After read a lot about it, I'm confused about if it is legal or not accessing to inactive member of an union starting from C++14. I understood it is undefined behaviour up to C++11.

Some references:

Unexpected behaviour using bit-fields and unions

Is it legal to use address of one field of a union to access another field?

C++14 introduced this statement:

"all non-static data members will have the same address"

(ref: https://en.cppreference.com/w/cpp/language/union)

Is it admissible to use an union like this?


typedef union _BYTE_VAL_T
{
    unsigned char Val;
    struct
    {
        unsigned char b0:1;
        unsigned char b1:1;
        unsigned char b2:1;
        unsigned char b3:1;
        unsigned char b4:1;
        unsigned char b5:1;
        unsigned char b6:1;
        unsigned char b7:1;
    } bits;
} BYTE_BITS_T;


int main()
{
   BYTE_BITS_T reg;
   reg.bits.b5 = 0x1;
   std::cout << reg.Val; // use of inactive member
}
0

There are 0 best solutions below