Bitfields in C
Struct members measured in bits, for packing flags and small counters.
#include <stdio.h>
typedef struct {
unsigned int visible : 1;
unsigned int locked : 1;
unsigned int stars : 2;
unsigned int tour : 4;
} StepFlags;
void flags(void) {
StepFlags f = {.visible = 1, .stars = 3, .tour = 11};
printf("size %zu\n", sizeof f);
printf("visible %u locked %u stars %u tour %u\n", f.visible, f.locked,
f.stars, f.tour);
f.stars = 4;
printf("wrapped stars to %u\n", f.stars);
}
How it works
- The width follows the member name after a colon.
- Packing order and padding are implementation defined.
- An unsigned type avoids surprises with the sign bit.
Keywords and builtins used here
flagsintsizeofstructtypedefunsignedvoid
The run, in numbers
- Lines
- 19
- Characters to type
- 401
- Tokens
- 113
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 68 seconds.
Step 3 of 5 in Unions & layout, step 3 of 13 in Unions, bitfields & undefined behavior.