Search code examples
c++c++11bit-fields

BitField Variable Syntax


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


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)