C Unions: Shared Memory Storage
A **Union** is a user-defined data type where all members share the same starting memory address. You can define a union with many members, but only **one member can contain a value at any given time**.
1. Defining and Declaring a Union
The syntax for a union is identical to a structure, but it uses the union keyword.
union Data {
int i;
float f;
char str[20];
};
int main() {
union Data data;
return 0;
}
2. Memory Allocation: Struct vs. Union
This is the most critical difference between the two. A structure's size is the sum of its members' sizes, whereas a union's size is the size of its largest member.
| Feature |
Structure |
Union |
| Keyword |
struct |
union |
| Memory |
Each member has its own location. |
All members share the same location. |
| Total Size |
Sum of all members. |
Size of the largest member. |
3. Accessing Union Members
Because members share memory, changing one member will overwrite the others. You must use one member at a time to avoid data corruption.
union Data data;
data.i = 10;
printf("data.i : %d\n", data.i); // Output: 10
data.f = 220.5;
printf("data.f : %.1f\n", data.f); // Output: 220.5
// Now data.i is corrupted because data.f took its spot!
printf("data.i after f: %d\n", data.i); // Output: Garbage value
4. Practical Use Cases
- Memory Efficiency: When you have a structure with many variables, but you know only one will be used at a time (e.g., a "Value" struct that can be a string OR an int OR a float).
- Hardware Access: Reading a 32-bit register as a single integer or as four individual 8-bit bytes.
- Variants: Implementing "Variant" types in compilers or interpreters.
5. Nested Unions
Just like structures, unions can be nested inside structures (often called "Tagged Unions") to keep track of which union member is currently active.
struct Token {
int type; // 0 for int, 1 for float
union {
int iVal;
float fVal;
} val;
};
Pro Tip: Always use a "Type Flag" (like in the example above) when using unions in professional code. Since C doesn't tell you which union member was last updated, a flag prevents you from accidentally reading an integer as a float and getting gibberish.