When to Use Union in C: Purpose and Examples
union in C when you want to store different data types in the same memory location, saving space by sharing memory among members. It is useful when only one of the member values is needed at a time.How It Works
A union in C is like a shared box where you can keep different things, but only one thing at a time. Instead of giving each item its own separate box (like a struct does), a union uses the same space for all its members. This means the size of the union is the size of its largest member.
Think of it like a multi-tool: it can be a knife, screwdriver, or bottle opener, but you only use one function at a time. When you store a new value in one member, it replaces the old value because they share the same memory.
Example
union holding an integer, a float, and a character array. Only one value is stored at a time, demonstrating how the memory is shared.#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
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);
strcpy(data.str, "Hello");
printf("data.str = %s\n", data.str);
// Note: After setting data.str, data.i and data.f may hold garbage values
return 0;
}When to Use
Use a union when you need to save memory by storing different types of data in the same space, but only one at a time. This is common in:
- Embedded systems where memory is limited.
- Handling different data formats in communication protocols.
- Implementing variant data types or tagged unions.
- Interpreting the same data in multiple ways, like reading raw bytes as integers or floats.
Unions help keep your program efficient and organized when you know only one value will be used at a time.
Key Points
- A
unionshares memory among all its members. - Only one member can hold a valid value at a time.
- Size of a
unionequals the size of its largest member. - Useful for saving memory and handling multiple data types flexibly.
- Be careful: writing to one member and reading from another can cause unexpected results.
Key Takeaways
union to save memory by sharing space among different data types.union holds a valid value at any time.union equals its largest member's size.