Loading lessons...
Unions
Unions
A union is like a struct, but all members share the same memory. Only one member has a value at a time.
Defining a union
union MyUnion {
int intNum;
float floatNum;
char str[20];
};
All members overlap
All fields start at the same address. Writing one overwrites the others:
union MyUnion u;
u.intNum = 42;
u.floatNum = 3.14; // intNum's value is now garbage
Why use unions?
- Save memory when only one form of data is needed at a time.
- Interpret the same bytes differently.
- Compact storage for variant data.
Union size
A union is as big as its largest member, not the sum.
TL;DR
- A union shares one memory block among all members.
- Only one member holds a meaningful value at a time.
- Writing one member destroys the others.
- Union size = its largest member.