c / intermediate
Snippet
Bitfields for Memory Optimization
Bitfields allow you to specify the exact number of bits used by structure members. This is highly efficient for storing flags or small integers where full types like 'int' (32 bits) would be wasteful. The compiler packs these fields into a single underlying storage unit.
snippet.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdio.h>struct Status {unsigned int isActive : 1;unsigned int errorCount : 3;unsigned int mode : 4;};int main() {struct Status s = {1, 5, 10};printf("Size: %zu bytes\n", sizeof(s));printf("Active: %u, Errors: %u, Mode: %u\n", s.isActive, s.errorCount, s.mode);return 0;}
Breakdown
1
unsigned int isActive : 1;
Allocates exactly 1 bit for this member (0 or 1).
2
unsigned int errorCount : 3;
Allocates 3 bits, allowing values from 0 to 7.
3
unsigned int mode : 4;
Allocates 4 bits, allowing values from 0 to 15.