Home / Learn Embedded C / Unions in C
Unions in C
A type where all fields share the same memory — used to reinterpret bytes in embedded code.
How to think about this
Definition
A union looks like a struct but all its fields share the exact same memory, so writing one field overwrites the others — only one field is meaningfully "valid" at a time.
Why you need this
Embedded code often needs to look at the same bytes two ways: as a 32-bit sensor value, or as 4 separate bytes to send one at a time over UART — a union does this with zero copying.
How it works
A union's size equals its largest field; writing through one member and reading through another reinterprets the same underlying bytes (useful, but easy to misuse if you are not careful about types).
Where you'll see this
- UART/SPI byte-splitting
- Protocol encoding
- Register reinterpretation
Try it
A union gives the compiler-level shortcut for this; shifting and masking gets the identical bytes out by hand.
#include <stdio.h>
union Reinterpret {
unsigned int as_int;
unsigned char as_bytes[4];
};
int main() {
union Reinterpret u;
u.as_int = 0x11223344;
for (int i = 0; i < 4; i++) {
printf("byte %d = 0x%02X\n", i, u.as_bytes[i]);
}
return 0;
}Try it: merging bytes back into a 16-bit value
A union would let you write high_byte/low_byte as bytes and read as_int directly; shifting and OR-ing reconstructs the same value by hand -- the reverse of the byte-splitting example above.
Test what you just read
1. What is the key difference between a struct and a union?
Struct fields are laid out one after another; union fields overlap in the same memory.