Search code examples
c++bit-fields

Why can't a bit field be split between different underlying types?


Why does the sizes of these two structs differ?

#pragma pack(push, 1)
    struct WordA
    {
        uint32_t address           : 8;
        uint32_t data             : 20;
        uint32_t sign              : 1;
        uint32_t stateMatrix : 2;
        uint32_t parity            : 1;
    };

    struct WordB
    {
        uint8_t address;
        uint32_t data             : 20;
        uint8_t sign              : 1;
        uint8_t stateMatrix : 2;
        uint8_t parity            : 1;
    };
#pragma pack(pop)

Somehow WordB occupies 6 bytes instead of four, while WordA occupies exactly 32 bits. I assumed that given the sum of used bits inside a struct would yield both structs to be of the same size. Apparently I am wrong, but I cannot find an explanation why. Bit fields page shows only examples when all of the struct members are of the same type, which is a case of WordA.

Can anybody explain, why the sizes don't match and if it is according to the standard or implementation-defined?


Solution

  • Why can't a bit field be split between different underlying types?

    It can in the sense that standard allows it.

    It wasn't because that's what the language implementer (or rather, the designer of the ABI) chose. This decision may have been preferred because it may make the program faster or the compiler easier to implement.

    Here is the standard quote:

    [class.bit]

    ... Allocation of bit-fields within a class object is implementation-defined. Alignment of bit-fields is implementation-defined. Bit-fields are packed into some addressable allocation unit.