Union
Overview
A Union is a non-primitive data type that allows a value to be one of several different types, but only one at a time. All members share the same memory location.
Unions are used when different data representations are needed, but never simultaneously.
What Is a Union?
A union:
- Defines multiple possible fields
- Stores only one active field at a time
- Uses shared memory for all fields
The size of a union is the size of its largest member.
How It Works
When a value is assigned:
- Memory is overwritten with the new value
- Previous content becomes invalid
- The program must track which field is active
Unions do not store type information by default.
Example
Pseudocode
union Data {
i: Integer
f: FloatingPoint
}
d.i = 10
d.f = 3.14 // overwrites integer value
Real-world Analogy
A union is like a single drawer that can hold different items, but only one fits at a time 🗄️.
Common Operations
- Assignment
- Field access
- Manual type tracking
- Memory reinterpretation
Time and Space Complexity
- Space: O(1)
- Access: O(1)
Use Cases
- Memory-constrained systems
- Low-level programming
- Variant data storage
- Hardware and protocol parsing
Advantages
- Memory efficient
- Flexible representation
- Fast access
Limitations
- Unsafe without type tracking
- Easy to misuse
- Debugging can be difficult
Union vs Struct
| Aspect | Union | Struct |
|---|---|---|
| Memory | Shared | Separate |
| Active fields | One | All |
| Safety | Low | High |