Unions in C
In the previous lessons, you learned about structures and nested structures.
Now we study a concept that looks similar to structures, but behaves very differently in memory.
This concept is called a union.
Why Do We Need Unions?
Sometimes, a program needs to store:
- Only one value at a time
- But of different possible types
Using a structure wastes memory in such cases.
Unions help optimize memory usage.
What Is a Union?
A union is a user-defined data type like a structure.
But the key difference is:
All members of a union share the same memory location.
Only one member can hold a valid value at a time.
Defining a Union
union Data {
int i;
float f;
char c;
};
This defines a union with three members.
Creating a Union Variable
union Data d1;
Memory is allocated based on the largest member.
Accessing Union Members
Access members using the dot operator, just like structures:
d1.i = 10;
d1.f = 3.14;
But remember:
Storing a new value overwrites the previous one.
Complete Example
#include <stdio.h>
union Data {
int i;
float f;
char c;
};
int main() {
union Data d;
d.i = 10;
printf("Integer: %d\n", d.i);
d.f = 3.5;
printf("Float: %.2f\n", d.f);
d.c = 'A';
printf("Char: %c\n", d.c);
return 0;
}
Each assignment replaces the previous value.
Union vs Structure (Conceptual)
Key differences:
- Structure → each member has separate memory
- Union → all members share memory
Structure size = sum of member sizes (plus padding) Union size = size of largest member
Memory Understanding
Example:
- int → 4 bytes
- float → 4 bytes
- char → 1 byte
Union size will be 4 bytes.
Structure size would be larger.
Real-World Analogy
Think of a TV remote display:
- It can show channel number
- Or volume level
- Or battery status
But only one thing is shown at a time.
That is how a union works.
Where Unions Are Used
- Embedded systems
- Low-level hardware programming
- Protocol parsing
- Memory-efficient applications
Mini Practice
- Create a union with int and char
- Assign values one by one
- Print after each assignment
Quick Quiz
Q1. What is the main purpose of a union?
To save memory by sharing storage.
Q2. Can a union store multiple values at once?
No.
Q3. Which determines the size of a union?
The largest member.
Q4. Do unions and structures use the same syntax?
Yes.
Q5. Are unions useful in real applications?
Yes, especially where memory is limited.