C Unions
A union looks similar to a struct syntactically, but all its members share the same memory location. This means a union only needs enough memory for its largest member, and only one member is valid at a time.
Unions are often used to save memory when you know only one of several possible types will be needed at any given moment, such as in variant types or low-level hardware programming.
union Name {
type member1;
type member2;
};Defining a union
A union is declared just like a struct but with the `union` keyword. All members overlap the same memory, so writing to one member can overwrite the data of another.
Union vs struct
A struct allocates separate memory for each member, so its size is the sum of all members. A union allocates memory equal to its largest member, since members share that space.
#include <stdio.h>
union Data {
int i;
float f;
};
int main() {
union Data d;
d.i = 10;
printf("%d\n", d.i);
return 0;
}10Writing to d.i stores 10 in the shared memory of the union.
#include <stdio.h>
union Data { int i; float f; };
int main() {
printf("%lu %lu\n", sizeof(union Data), sizeof(int));
return 0;
}4 4The union's size equals its largest member (int and float are both 4 bytes here).
Key points
- All union members share the same memory location.
- A union's size equals the size of its largest member.
- Only one union member should be treated as valid at a time.
- Unions are useful for memory-efficient variant data.
