Unions in C
Unions in C
Introduction
In C programming, a union is a user-defined data type similar to a structure.
But unlike structures, all members share the same memory location.
👉 This helps in saving memory.
What is a Union?
A union is:
👉 A user-defined data type where all members share the same memory location
Why Use Unions?
- ✔ Save memory
- ✔ Store different types at different times
- ✔ Efficient memory usage
- ✔ Useful in embedded systems
Syntax of Union
union union_name {
data_type member1;
data_type member2;
};
Example: Union Declaration & Usage
#include <stdio.h>
union Data {
int i;
float f;
char str[20];
};
int main() {
union Data d;
d.i = 10;
printf("Integer = %d\n", d.i);
d.f = 5.5;
printf("Float = %.1f\n", d.f);
return 0;
}
Output
Integer = 10
Float = 5.5
⚠️ Important Note
👉 Only one member holds value at a time
👉 Changing one value overwrites others
Example Showing Overwrite
#include <stdio.h>
union Data {
int i;
float f;
};
int main() {
union Data d;
d.i = 10;
d.f = 3.5;
printf("i = %d\n", d.i);
printf("f = %.1f\n", d.f);
return 0;
}
Output
i = (garbage value)
f = 3.5
👉 i value is lost
Structure vs Union Table
| Feature | Structure | Union |
|---|---|---|
| Memory | Separate memory | Shared memory |
| Usage | All members usable | One at a time |
| Size | Sum of members | Largest member |
Important Notes
- Only one member is valid at a time
- Union size = largest data member
- Saves memory but limits usage
Common Mistakes
- ❌ Using multiple members together
- ❌ Expecting all values to be stored
- ❌ Confusing with structure
- ❌ Wrong memory understanding
Pro Tips
- ✔ Use unions when memory is limited
- ✔ Use structures for multiple values
- ✔ Understand memory sharing
- ✔ Practice union examples
Conclusion
Unions are useful for memory optimization in C programming. They allow efficient use of memory when only one value is needed at a time.
Use unions wisely for better performance.
👉 This article is part of Dharani Tech Edu Hub — where learning programming is made simple and practical.
Comments
Post a Comment