When bit-fields are useful
suggest changeBit-fields provide named access to small integer fields inside a structure:
struct options {
unsigned mode : 2; /* Values 0 through 3. */
unsigned enabled : 1; /* Values 0 or 1. */
unsigned priority : 3; /* Values 0 through 7. */
};
They can be convenient for compact, implementation-local state. Assigning a value that is not representable in an unsigned bit-field converts it according to the rules for the field's type; it is not automatically undefined behavior. Validate inputs when truncation would be a bug.
struct options option = {0};
option.mode = 2;
option.enabled = 1;
Bit-field layout is implementation-defined. The implementation chooses details such as allocation-unit alignment, whether fields can cross unit boundaries, and the ordering of fields within a unit. The signedness of a plain int bit-field is also implementation-defined, so use signed or unsigned explicitly when it matters.
These properties make bit-fields unsuitable as a portable network-packet, device-register, or file-format representation. For external formats, store bytes or fixed-width unsigned integers and use masks and shifts defined by the format. Avoid type-punning a bit-field structure through a union: padding and layout still prevent a portable mapping.
Individual bit-fields have no address, so the unary & operator cannot be applied to one. Concurrent updates to neighboring fields may also access the same storage unit and require synchronization.