C bit fields pack individual bits into struct members, saving memory when many boolean or small-range fields are needed. Declare with unsigned type : nbits to allocate exactly N bits for the field.
Use bit fields for hardware registers, flags, or tight memory constraints.
// compile: gcc -o bitfields bitfields.c // run: ./bitfields // description: packing bits into struct #include <stdio.h> struct Flags { unsigned enabled : 1; unsigned mode : 2; unsigned priority : 3; unsigned reserved : 2; }; struct Register { unsigned int addr : 16; unsigned int flags : 8; unsigned int status : 8; }; int main() { struct Flags f; f.enabled = 1; f.mode = 2; f.priority = 5; printf("Flags size: %zu bytes\n", sizeof(f)); printf("Register size: %zu bytes\n", sizeof(struct Register)); return 0; }
Bit field declarations:
unsigned type: nbits: N-bit fieldPortability issues:
Limitations:
&)Best uses: