tuzzer tuzzer - 4 years ago 120
C++ Question

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

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download