What is Union in C: Definition, Usage, and Examples
union is a special data type that allows storing different data types in the same memory location. Only one member of the union can hold a value at a time, sharing the same memory space for all members.How It Works
A union in C is like a shared box where you can keep one item at a time, but the box is big enough to hold the largest item you might want to store. Unlike a struct where each member has its own space, all members of a union overlap in memory.
This means if you change one member, it affects the others because they share the same memory. Think of it as a multi-tool where only one tool can be used at a time, but all tools share the same handle.
Example
This example shows a union with an integer and a float. We assign a value to the integer member, then to the float member, and print both to see how the shared memory works.
#include <stdio.h>
union Data {
int i;
float f;
};
int main() {
union Data data;
data.i = 10;
printf("data.i = %d\n", data.i);
data.f = 220.5f;
printf("data.f = %.1f\n", data.f);
// Now printing data.i again shows unexpected value
printf("data.i after assigning data.f = %d\n", data.i);
return 0;
}When to Use
Use a union when you need to store different types of data but only one at a time, saving memory. This is useful in situations like:
- Handling different data formats in the same memory space.
- Implementing variant data types or tagged unions.
- Working with hardware registers or protocols where data interpretation changes.
It helps reduce memory usage compared to using separate variables for each type.
Key Points
- A
unionshares the same memory for all its members. - Only one member can hold a meaningful value at a time.
- Memory size of a
unionequals the size of its largest member. - Changing one member affects the others because of shared memory.
- Useful for saving memory when storing different types alternatively.