Unions and Bit Fields
A union stores different types in the same memory. Bit fields pack several small values into one integer. Both save space and map to hardware.
Example
#include <stdio.h>
union Num { int i; float f; };
struct Flags { unsigned a : 1; unsigned b : 3; unsigned c : 4; };
int main(void) {
union Num n; n.f = 1.0f;
printf("%d\n", n.i == 0x3f800000);
struct Flags f = {1, 5, 9};
printf("%u %u %u %zu\n", f.a, f.b, f.c, sizeof f);
return 0;
}Result
1 1 5 9 4
Exercise
Share memory.
Num { int i; float f; };Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.