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?
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_fVar
1 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.
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.
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