How do unions differ from structures in memory layout?
All union members live at offset 0 and overlap the same storage; the union's size is its largest member, not the sum.
* A struct gives each member its own bytes (size = sum + padding); a union overlays members on the same bytes (size = max). *
A struct gives each member its own slot side by side; a union overlays every member on the same bytes. Only one member is meaningfully "active" at a time — writing one overwrites the others because they share storage.
union { float f; unsigned int u; } fu; // f and u occupy the SAME 4 bytes
Struct vs. union for the same two members:
Struct: | f | pad | u | size 12 (members side by side)
Union: | f OR u | size 4 (members overlap)
0 4
| Aspect | Struct | Union |
|---|---|---|
| Member offset | Cumulative (each after the previous) | All 0 |
| Size | Sum of members + padding | max(sizeof(member_i)) |
| Alignment | Max member alignment | Max member alignment |
| Members | Independent | Share the same bytes |
Use cases: memory-efficient "variant" records (store one of several types in the same space), and type punning — reading the same bits through a different type instead of converting the value.
Go deeper:
Union type (Wikipedia) — the union type and its overlaid members.
Type punning (Wikipedia) — type punning, the classic union use case.