Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does union in C++ do in this case?

Tags:

c++

unions

In one of the classes that I am working I found some thing like this in the header file:

// Flags
union
{
    DWORD               _flags;
    struct {
        unsigned        _fVar1:1;
        unsigned        _fVar2:1; 
        unsigned        _fVar3:1; 
        unsigned        _fVar4:1;  
    };
};

In some of the class's member functions, I have seen _flags being set directly like _flags = 3;. I have also seen the members in the struct being set directly, like _fVar1 = 0 and being compared against.

I am trying to remove _fVar1, I am not sure what it will do to other places where _flags and other _fVar# are accessed or set. For instance, does setting _flags = 3 means that _fVar1 and _fVar2 will be 1 and _fVar3 and _fVar4 will be 0? Would removing or adding to the struct means I have to make corresponding changes to codes that touches any of the other members in the union?

like image 539
tuzzer Avatar asked Mar 10 '23 03:03

tuzzer


2 Answers

Anonymous member structs (classes) are not allowed in C++, so the program is ill-formed as far as the standard is concerned.

Accessing non-active member of a union has undefined behaviour.

So in short: Whatever it does is up to the compiler.


Both of those are allowed in C (the former wasn't allowed until C11, the latter until C99), and by some compilers, as an extension in C++ (and as an extension in earlier versions of C). Let us assume that you use such compiler.

For instance, does setting _flags = 3 means that _fVar1 and _fVar2 will be 1 and _fVar3 and _fVar4 will be 0?

That is probably the intention. However, the behaviour depends on the representation that the compiler has chosen for the bit fields.

Without making assumptions about the representation, the only sensible thing that you can use the union for is to set all flags to 0 (_flags = 0), or all flags to 1 (_flags = -1).

Would removing or adding to the struct means I have to make corresponding changes to codes that touches any of the other members in the union?

Yes, unless the code touches all of the members equally, like the two examples above.

like image 199
eerorika Avatar answered Mar 19 '23 22:03

eerorika


There is nothing very special about it. This is simply a union of an integer variable and a struct with bit fields.

Every bitfield in the struct is one bit length, so it can be used to access individual bits in the integer.

like image 45
SergeyA Avatar answered Mar 20 '23 00:03

SergeyA