Question

I am interested in the syntax convention for BitFields in C++ and if different methods of naming variables need to be accounted for in the number of allocated bits.

union BitField32
{
    struct {
        unsigned int a : 1;
        unsigned int b : 1;
    };
    unsigned int data;
};
BitField32 Flags;

vs

union BitField32
{
    struct {
        unsigned int a, b : 1;
    };
    unsigned int data;
};
BitField32 Flags;

Does naming the variables in the bottom example require the use of two bits or are they allocated a single bit

Was it helpful?

Solution

There are not equivalent:

With:

struct S1 {
    unsigned int a : 1;
    unsigned int b : 1;
};

struct S2 {
    unsigned int a : 1, b : 1;
};

struct S3 {
    unsigned int a;
    unsigned int b : 1;
};

struct S4 {
    unsigned int a, b : 1;
};

We have S1 and S2 which are equivalent, and S3 and S4 which are equivalent.
S1 and S3 are not. (https://ideone.com/6Jvh36)

OTHER TIPS

Taking the pieces of code one at a time.

union BitField32
{
    struct {
        unsigned int a : 1;
        unsigned int b : 1;
    };
    unsigned int data;
};
BitField32 Flags;

This is the union of a struct containing two bit flags, with an unsigned int. The C++ standard guarantees that the two bit flags will be packed into some kind of allocation unit, but makes no guarantees about the size of that unit, the allocation of the bit fields or their alignment. In particular, both high to low and low to high allocation of bits are commonplace.

So trying to use bit fields to pick out bits in an unsigned int is implementation defined. If it works on one compiler, it may not work on another. Use it if you must, but be very careful.

union BitField32
{
    struct {
        unsigned int a, b : 1;
    };
    unsigned int data;
};
BitField32 Flags;

This code is almost guaranteed to be wrong. It is the union of a struct containing an unsigned int and a single bit flag, with an unsigned int. Not only are they not allocated a single bit, they aren't even packed into a single unsigned int.

The C++ standard says that the bit-field attribute is not part of the type. If you thought it would be similar to the first sample, it's not. Do not write code like this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top