C Unions โ Efficient Memory Sharing in C
Introduction โ What Is a Union in C?
In C programming, a union is a user-defined data type that allows multiple members to share the same memory location. While similar in syntax to a struct, a union stores only one value at a time, making it ideal for memory-constrained environments or scenarios where only one field is needed at any given moment.
In this guide, youโll learn:
- The syntax and behavior of unions
- How they differ from structures
- Real-world examples and memory advantages
- Best practices and use cases
Core Concept โ How a Union Works
All members of a union occupy the same memory space, and its total size is equal to the size of its largest member. Assigning a value to one member overwrites the data of the others.
Syntax:
union Data {
int i;
float f;
char str[20];
};
Only one member should be used at a time.
Code Examples โ Using Unions
Example 1: Accessing Union Members
#include <stdio.h>
union Data {
int i;
float f;
char str[20];
};
int main() {
union Data d;
d.i = 10;
printf("d.i = %d\n", d.i);
d.f = 3.14;
printf("d.f = %.2f\n", d.f);
strcpy(d.str, "C Language");
printf("d.str = %s\n", d.str);
return 0;
}
Output (varies):
d.i = 10
d.f = 3.14
d.str = C Language
After assigning to d.str, previous values (d.i and d.f) become overwritten/undefined.
Use Cases of Unions
| Use Case | Why Use Union? |
|---|---|
| Variant data types | Store different types in the same memory |
| Embedded systems | Save memory in small devices |
| Protocol parsers | Interpret memory differently (byte/word) |
| Interfacing with hardware | Access data registers as multiple formats |
Union vs Structure
| Feature | Structure (struct) | Union (union) |
|---|---|---|
| Memory usage | Sum of all members | Size of largest member |
| Simultaneous access | Multiple members | Only one member at a time |
| Use case | Group related data | Save space when only one field used |
Best Practices & Tips
Best Practice:
Use unions in scenarios where only one member is active at a time.
Tip:
Combine union with struct or enum to create tagged unions (safe type tracking).
Pitfall:
Reading from a union member that wasnโt last written to results in undefined behavior.
Real-World Applications
- Compiler construction (AST nodes, token values)
- Device drivers and register-level programming
- Communication protocols (packet layout interpretation)
- Game engines (variant object states)
Summary โ Recap & Next Steps
Unions are powerful tools for optimizing memory when working with exclusive-use variables. While similar to structs in declaration, their behavior makes them suited for specialized scenarios.
Key Takeaways:
- Unions share memory between all members
- Only one member holds valid data at a time
- Best for memory-saving and low-level access
- Use carefully to avoid overwriting or reading stale data
Real-World Relevance:
Crucial in embedded development, memory-mapped IO, network parsers, and binary format interpreters.
Frequently Asked Questions (FAQ)
What is a union in C?
A user-defined type where all members share the same memory location, allowing only one active value at a time.
How is union different from structure?
A struct stores all members simultaneously; a union stores one at a time, reusing memory.
What happens if I access a union member that wasnโt last assigned?
You get undefined behavior. Only the last assigned member is guaranteed valid.
Can unions be nested inside structures?
Yes. You can create complex types by combining unions and structs.
When should I use a union?
When only one of several members is used at any time and memory efficiency is important.
Share Now :
