Search code examples
cbit-fieldsimplementation-defined-behavior

What does the C specification mean with "overlap adjacent units" in the context of bitfields?


I'm struggling to understand this section on bitfields of the C language specification (6.7.2.1.11):

An implementation may allocate any addressable storage unit large enough to hold a bit-field. If enough space remains, a bit-field that immediately follows another bit-field in a structure shall be packed into adjacent bits of the same unit. If insufficient space remains, whether a bit-field that does not fit is put into the next unit or overlaps adjacent units is implementation-defined. [...]

I always programmed under the assumption that overflowing bitfields are moved onto the next allocation unit; e.g.

struct {
    uint8_t bits0_3 : 4;
    uint8_t bits4_7 : 4;
    uint8_t overflowing: 1; // <-- this bit will overflow into a second byte
};

However, this paragraph specifies that the implementation may decide to make it "overlap adjacent units". What does this mean exactly? Could the overflowing bit overlap with bits0_3 as if in a union?


Solution

  • What they mean is this: If the bit-field does not fit entirely into the storage unit of the previous bit-field, then it can (1) Skip to the next storage unit and place the bit-field there, or (2) It can split it up, placing part of it in the previous storage unit and the rest in the next storage unit. That's what they mean by "overlaps adjacent units".

    For example, suppose you have:

    struct {
        uint8_t a:5;
        uint8_t b:6;
        uint8_t c:3;
    }
    

    One way to pack these fields is in 3 separate 8-bit integers, with a, b, and c each placed in its own 8-bit integer. But it could also split them so that a and 3 bits of b are in the first 8-bit integer, and the other 3 bits of b, along with c, are placed in a second 8-bit integer.