Unions in C Programming
Unions in C Programming
Introduction to Unions in C Programming
Unions in C programming are user-defined data types similar to structures, but they store all members in the same memory location. This helps in saving memory when different data types are used at different times.
Unions in C programming are useful in memory optimization and low-level programming.
What is Union in C Programming
A union is a data type where all members share the same memory location. At any time, only one member can hold a value.
Syntax of Union in C Programming
data_type member1;
data_type member2;
};
Example: Basic Union
union Data {
int i;
float f;
char c;
};
int main() {
union Data d;
d.i = 10;
printf(“Integer: %d\n”, d.i);
d.f = 5.5;
printf(“Float: %f\n”, d.f);
d.c = ‘A’;
printf(“Character: %c\n”, d.c);
return 0;
}
Key Concept of Union Memory
All members share the same memory.
union Test {
int a;
float b;
};
int main() {
union Test t;
t.a = 10;
printf(“a = %d\n”, t.a);
t.b = 2.5;
printf(“b = %f\n”, t.b);
// Value of a is now overwritten
printf(“a (after b) = %d”, t.a);
return 0;
}
Size of Union
The size of a union is equal to the size of its largest member.
union Example {
int a;
double b;
char c;
};
int main() {
printf(“Size of union = %lu”, sizeof(union Example));
return 0;
}
Union vs Structure
Union
- Shared memory
- One member at a time
- Memory efficient
Structure
- Separate memory
- All members usable
- More memory usage
Practical Example of Union
union Student {
int id;
float marks;
};
int main() {
union Student s;
s.id = 101;
printf(“ID: %d\n”, s.id);
s.marks = 85.5;
printf(“Marks: %.2f”, s.marks);
return 0;
}
Advantages of Unions in C Programming
Key Benefits
- Saves memory
- Useful in embedded systems
- Efficient data storage
- Suitable for low-level programming
Common Mistakes
Avoid These Errors
- Using multiple members at same time
- Misunderstanding memory sharing
- Overwriting data unintentionally
Best Practices
Tips
- Use union when only one value is needed at a time
- Combine with structures when required
- Understand memory behavior clearly
Start Learning C Programming
Practice unions in C programming to understand memory optimization techniques.
Summary
Unions in C programming allow multiple data types to share the same memory. They are useful for memory optimization and efficient data handling.
FAQs
What is union in C programming?
A data type where all members share same memory.
Can we use all members at same time?
No.
Why use union?
To save memory.
What is size of union?
Size of largest member.



