What Are Unions?
A
union is like a struct, but all members share the same memory. The size of a union equals the size of its largest member. Only one member can hold a valid value at a time.c
Key Difference: In astruct, each member has its own memory. In aunion, all members overlap. Writing to one member clobbers the others.
Tagged Unions (Discriminated Unions)
The most common pattern: combine a union with an enum tag to track which member is active:
c
This pattern is the C equivalent of a "variant" or "sum type" and is used extensively in interpreters, parsers, and protocol handlers.
When to Use Unions
- Memory efficiency — when you need to store different types in the same slot
- Type-punning — interpreting the same bytes as different types
- Protocol parsing — network packets with variant payloads
- Interpreter values — a single
Valuetype that can be int, float, or string
Summary
| Concept | Key Point |
|---|---|
| Memory | All members share the same bytes |
| Size | Equals the largest member |
| Active member | Only one holds valid data at a time |
| Tagged union | Combine with enum to track active type |
| Use cases | Variants, parsers, memory-efficient storage |