What are bit-fields and what are their drawbacks?
Short answer: Bit-fields let you declare struct members that are a given number of bits wide, so several flags or small values share one word and can be accessed by name. Their drawbacks are that bit order, padding, whether a field can cross a storage unit, and the signedness of plain int fields are all implementation-defined, and writing one field is a non-atomic read-modify-write of the whole storage unit.
struct status {
unsigned ready : 1;
unsigned error : 1;
unsigned mode : 3; /* values 0..7 */
unsigned : 3; /* unnamed padding bits */
};
struct status s = {0};
s.mode = 5;
s.ready = 1;
Advantages: compact storage (e.g. thousands of flags in a table), readable code, the compiler generates the masks and shifts.
Drawbacks in detail
- Layout is not portable: one compiler puts the first field at the least significant bit, another (or the same compiler on a big-endian target) at the most significant. This makes bit-fields unsuitable for matching hardware registers or network formats across compilers.
- Access width: the compiler may use a byte or halfword access to update a field. Some peripheral registers only accept 32-bit accesses. (GCC's
-fstrict-volatile-bitfields, the default for Arm EABI, uses the declared type's width for volatile bit-fields, which helps but is still compiler-specific.) - Not atomic:
s.ready = 1reads the word, modifies one bit and writes it back. If an ISR modifiess.errorin between, the update is lost. - No address:
&s.modeis not allowed, and there are no arrays of bit-fields. - Signedness:
int x : 3;may be signed or unsigned depending on the compiler. Always useunsigned(or_Bool) explicitly.
What most embedded teams do: use explicit masks and shifts (#define CTRL_MODE_Pos 2, #define CTRL_MODE_Msk (7u << CTRL_MODE_Pos)) for hardware registers and wire formats, and use bit-fields only for internal data whose layout does not matter.
Note: some vendor headers (e.g. TI C2000, older Microchip) do define registers as bit-field unions; that works because the vendor controls the compiler. Do not copy the pattern to portable code.