Example 1 — Packing three values
Each field stores only its allowed range.
#include <stdio.h>
struct Flags {
unsigned ready : 1;
unsigned mode : 3;
unsigned level : 4;
};
int main(void) {
struct Flags f = {1, 5, 9};
printf("ready=%u mode=%u level=%u\n", f.ready, f.mode, f.level);
f.mode = 7;
printf("mode=%u\n", f.mode);
printf("sizeof Flags = %zu\n", sizeof f);
return 0;
} How It Works
- The three fields use 1 + 3 + 4 = 8 bits.
- GCC and Clang store them in one
unsignedunit, so the size is typically 4 bytes. - Assigning a value too large for the width wraps or is implementation-defined, so keep to the range.
