Search topics...
C / C++ ConceptsStructs, Unions, and Alignmentfoundational

Why are bitfields problematic for hardware register access?

0 upvotes
Practice with AISoon

Bitfields have three major portability issues that make them unreliable for hardware registers:

  1. Bit ordering is implementation-defined — the compiler chooses whether the first field occupies the MSB or LSB. Different compilers (or even different versions of the same compiler) may lay out bits in the opposite order.
  2. Storage unit boundaries are compiler-dependent — a bitfield that spans a byte or word boundary may or may not be split across storage units.
  3. Read-modify-write behavior — the compiler may read the entire register word, modify the bitfield, and write back, potentially overwriting volatile status bits in other fields.

The portable alternative is explicit mask-and-shift: reg = (reg & ~MASK) | (value << SHIFT);. MISRA C Advisory Rule 6.1 discourages bitfields for any hardware-interfacing code.

Source: C / C++ Concepts Q&A