In the previous topic, we learned about structures, which allow us to store different types of data together.
A union also allows us to group different data types, but there is one important difference: all members of a union share the same memory location.
What is a Union?
A union is a user-defined data type in C where all members share the same memory location.
It is defined using the union keyword:
union Data
{
int number;
float price;
char grade;
};
We can create a union variable:
union Data data;
How Does a Union Work?
Consider:
union Data
{
int number;
float price;
};
If we store a value in number:
data.number = 10;
we can access number.
But if we then store:
data.price = 20.5;
the same memory is used for price, so the previously stored number value is no longer reliably available.
C does allow reading number at this point, but you do not get 10 back. The bytes of the float 20.5 are simply reinterpreted as an int (on a typical system with a 4-byte int and IEEE 754 float, this prints 1101266944). The result depends on the platform, so in normal code we read only the member that was stored last.
Think of it like a single box that can hold different types of things, but only one is meant to be stored at a time.
Example
#include <stdio.h>
union Data
{
int number;
float price;
};
int main()
{
union Data data;
data.number = 10;
printf("Number: %d\n", data.number);
data.price = 20.5;
printf("Price: %.1f\n", data.price);
return 0;
}
Output:
Number: 10
Price: 20.5
The important point is that number and price use the same memory area.
Union vs Structure
This is the most important difference to remember.
Structure | Union |
|---|---|
Each member has separate storage | Members share storage |
Multiple members can hold valid values at the same time | Only the most recently stored member should be read |
Usually requires enough memory for all members | Size is based on its largest member, subject to alignment |
|
|
For example:
struct Data
{
int number;
float price;
};
Both number and price have their own storage.
But:
union Data
{
int number;
float price;
};
They share the same storage.
Why Use Unions?
Unions are useful when:
Only one member needs to be used at a time.
Memory efficiency is important.
Working with low-level or embedded systems.
Representing data that can have different possible types.
In Simple Words
A structure stores all its members separately, while a union makes all its members share the same memory location.
The easiest way to remember:
Structure → Separate memory
Union → Shared memory