C Unions
C Unions
A union is a special type that store different data types in the same memory location.
Unions are similar to structs, but with a key difference:
- In a
struct
, each member has its own memory. - In a
union
, all members share the same memory.
Most of the time, you will use structs instead of unions, as it can store and access multiple values at the same time, which is more common in everyday programs.
However, unions are useful when you only need to store one of several possible types at a time, and you want to save memory.
Declare a Union
To create a union, use the union
keyword, and then create a variable from it (just like with structs):
Example
union
myUnion { // Union declaration
int myNum; // Member
(int)
char myLetter; // Member (char)
char myString[30]; // Member (char array)
};
int main() {
union myUnion u1;
// Create a union variable with the name "u1":
return 0;
}
Access Union Members
And just like with structs, to access members of a Union, use the dot .
syntax.
Important: Since all members share the same memory, changing one will affect the others. Only the last assigned member holds a valid value:
Example
union myUnion {
int myNum;
char myLetter;
char
myString[30];
};
int main() {
union myUnion u1;
u1.myNum = 1000;
// Since this is the last value written to the union, myNum no
longer holds 1000 - its value is now invalid
u1.myLetter = 'A';
printf("myNum: %d\n", u1.myNum); // This value is no longer
reliable
printf("myLetter: %c\n", u1.myLetter); // Prints 'A'
return 0;
}
Try it Yourself »
Size of a Union
The size of a union will always be the same as the size of its largest member:
Example
union myUnion {
int myNum;
char myLetter;
char
myString[36];
};
int main() {
union myUnion u1;
printf("Size of
union: %lu bytes\n", sizeof(u1));
return 0;
}
Try it Yourself »
Since the largest member is 36 bytes, the entire union will also be 36 bytes.
If it was a struct
instead, the size would be 44 bytes:
myNum
(4 bytes) + myLetter
(4 bytes) + myString
(36 bytes) = 44 bytes total
When to Use Unions
Use unions when:
- You need to store different types in the same location
- You only use one type at a time
- Saving memory is important
Struct vs. Union
Feature | Struct | Union |
---|---|---|
Memory for each member | Separate | Shared |
Size of object | Sum of all members | Size of largest member |
Stores multiple values | Yes | No (only one at a time) |