๐งฌ 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 :