Unions
Learn how Unions allow multiple members of different data types to share the same memory location for maximum memory efficiency.
Introduction
In the previous lesson, you learned about Structures, which allow multiple variables of different data types to be grouped together. However, every member of a structure occupies its own memory. In situations where only one member is required at a time, allocating separate memory for every member wastes memory. To solve this problem, C provides Unions.
What is a Union?
A Union is a user-defined data type in which all members share the same memory location. Unlike a structure, a union allocates memory only once, and all members use that shared memory. At any given time, only one member can hold a meaningful value.
Why Do We Need Unions?
- Reduce memory usage
- Store different types of data in the same memory location
- Build memory-efficient applications
- Optimize embedded and system-level programs
Real-World Analogy
Imagine a conference room. The same room is used for different purposes at different times: in the morning for a team meeting, in the afternoon for training, and in the evening for a presentation. Similarly, in a union, the same memory location is used by different members, but only one member is meaningful at a time.
Characteristics of Unions
- User-defined data type
- Members can have different data types
- All members share the same memory
- Only one member should be used at a time
- Memory size equals the size of the largest member
Union Representation
Suppose a union contains an Integer, a Float, and a Character. All members use the same memory block:
Shared Memory
+-----------------------+
| int |
| float |
| char |
+-----------------------+
(All members overlap in this single block)Structure vs Union
| Feature | Structure | Union |
|---|---|---|
| Memory | Each member has separate memory | All members share the same memory |
| Simultaneous Values | Multiple members can store values | Only one member holds a valid value |
| Memory Usage | Larger memory usage | Smaller memory usage |
| Best For | Storing complete objects | Memory optimization |
Memory Allocation: Structure vs Union
Structure Memory
+---------+ | int (4) | +---------+ | float(4)| +---------+ | char (1)| +---------+ Total: 9 Bytes
Union Memory
+----------------+ | int / float | | / char | +----------------+ Total: 4 Bytes (Largest member)
Memory Size of a Union
The size of a union is determined by its largest member. For example, if a union contains a char (1 Byte), an int (4 Bytes), and a float (4 Bytes), the union size will typically be 4 Bytes.
Declaring and Accessing Unions
A union is declared using the union keyword. Like structures, a union definition acts as a blueprint, and memory is allocated only when a union variable is created. Members are accessed using the Dot (.) Operator.
union UnionName
{
data_type member1;
data_type member2;
};
// Accessing:
unionVar.member1 = value;Example: Creating a Union
#include <stdio.h>
union Data
{
int number;
float price;
char grade;
};
int main()
{
union Data data;
data.number = 100;
printf("Number : %d\n", data.number);
data.grade = 'A';
printf("Grade : %c", data.grade);
return 0;
}Line-by-Line Explanation
Lines 3-8: union Data { ... }
Defines a union named Data. Although there are three members—number, price, and grade—they all share the same memory location.
Line 11: union Data data;
Creates a union variable named data. Memory is allocated based on the largest member, which is typically 4 bytes for int or float.
Line 13: data.number = 100;
Stores the integer value 100 in the shared memory.
Line 17: data.grade = 'A';
The same memory is now used to store the character 'A'. The previous integer value is overwritten.
Memory Representation
Before assigning grade
Shared Memory +----------------+ | 100 | +----------------+
After assigning grade
Shared Memory +----------------+ | A | +----------------+ (100 is overwritten!)
Program Execution Flow
Expected Output
Number : 100
Grade : AAdvantages & Limitations
Advantages
Limitations
Real-World Applications
Embedded Systems
Sensor data and hardware registers.
Device Drivers
Register mapping and memory optimization.
Network Programming
Packet processing.
Operating Systems
Memory management and resource optimization.
Compilers
Efficient storage of different token types.
Common Beginner Mistakes
In a structure, each member has separate memory. In a union, all members share the same memory.
When a new value is assigned to one member, the previous member's value is overwritten.
If all members need to store values simultaneously, use a structure, not a union.
Always remember that every member occupies the same shared memory location.
Best Practices
- Use unions only when members are used one at a time.
- Choose structures when all members must retain their values.
- Use meaningful union names.
- Document which member is currently active.
- Prefer unions only when memory optimization is important.
Frequently Asked Questions
What is a union?
A union is a user-defined data type where all members share the same memory location.
How is a union different from a structure?
A structure allocates separate memory for each member, while a union allocates one shared memory block for all members.
Can all union members store values at the same time?
No. Only one member should contain a valid value at any given time.
How is the size of a union determined?
The size of a union is equal to the size of its largest member.
When should I use a union?
Use a union when different data types are required, but only one of them needs to be stored at a time.
Key Takeaways
- A union is a user-defined data type.
- All members share the same memory location.
- Only one member should hold a meaningful value at a time.
- The size of a union is determined by its largest member.
- Unions are useful for memory optimization and embedded programming.
Summary
Unions provide an efficient way to manage memory by allowing multiple members of different data types to share the same memory location. Unlike structures, where each member has its own storage, unions reuse a single memory block, making them ideal for applications where only one value is needed at a time. Understanding the differences between structures and unions helps programmers choose the most appropriate data type for building efficient and optimized C programs.