c / intermediate
Snippet
Memory Efficiency with Unions
A union allows different data types to be stored in the same memory location. The size of the union is determined by its largest member. This is particularly useful in systems programming for overlaying data structures or accessing specific parts of a memory word.
snippet.c
1
2
3
4
5
6
7
union HardwareRegister {uint32_t full_word;struct {uint16_t lower_half;uint16_t upper_half;} parts;};
Breakdown
1
union HardwareRegister
Defines a union where all members start at the same memory address.
2
uint32_t full_word;
Accesses the entire 32-bit memory block as a single integer.