Union in C Language (Memory Sharing Explained)
Table of Contents
Union in C language is a special user-defined data type. It allows multiple variables to share the same memory location. This makes unions different from structures in an important way.
In structures, each member gets separate memory space. In unions, all members overlap and share one memory block. Only one value remains valid at any given time.
This concept is known as memory sharing in C programming.
What Is a Union?
A union in C language is similar to a structure syntactically.
However, the internal memory behaviour is completely different.
All members of a union occupy the same memory address.
Writing one member automatically overwrites the previous value.
In simple comparison:
- Structure → Separate memory per member
- Union → Shared memory among members
Because of this behaviour, unions are mainly used in low-level programming.
Syntax of Union in C
The syntax of a union looks very similar to a structure.
The only difference is the keyword used.
union Data {
int i;
float f;
char name[20];
};All members declared inside the union share the same memory. The compiler allocates space equal to the largest member size. This similarity in syntax often confuses beginners initially.
Memory Allocation and Layout of Union in C
Memory allocation is the most important concept here. Understanding this makes unions easy to grasp.
In structures:
Memory equals sum of all member sizes.
In unions:
Memory equals size of the largest member only.
Example:
union Example {
int i; // 4 bytes
float f; // 4 bytes
char c; // 1 byte
};Total memory allocated = 4 bytes.
Even though three members exist, memory stays minimal.
Why This Happens
All members start at the same memory address.
Each assignment overwrites previously stored data completely.
This behaviour enables memory sharing in C programs.
Union vs Structure in C
This is a very common exam and interview topic.
Students are often asked to compare both clearly.
| Feature | Structure | Union |
| Memory allocation | Separate per member | Shared memory |
| Total size | Sum of members | Largest member only |
| Multiple values | Possible | Not possible |
| Data safety | Higher | Lower |
| Use case | General programs | Memory optimization |
Understanding this table removes most beginner confusion. Many learners search for the difference between union and structure in C because both look similar syntactically. However, their memory models are completely different. While structures allocate separate memory for each member, unions allow memory sharing, making them suitable for low-level and embedded programming scenarios.
Union Example in C
Let us look at a simple working example.
This helps clarify union behaviour quickly.
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main() {
union Data data;
data.i = 100;
printf("Integer: %d\n", data.i);
data.f = 5.5;
printf("Float: %.2f\n", data.f);
strcpy(data.str, "Union Demo");
printf("String: %s\n", data.str);
return 0;
}What This Example Shows
Each assignment replaces the previous stored value. All members share the same memory location internally.
After storing the string:
- Integer becomes invalid
- Float becomes invalid
This demonstrates memory sharing clearly.
How Memory Sharing Works Internally
Let us visualize what happens internally. Assume the union starts at memory address 1000.
Step-by-step behaviour:
- Store integer → Memory stores integer bytes
- Store float → Same bytes overwritten
- Store string → Memory reused again
All members map to the same memory region always.
This overlapping layout defines union behaviour.
When and Why to Use Union in C Programming
Union in C language should be used carefully.
It is ideal only in specific scenarios.
Memory-Constrained Systems
Used heavily in embedded and firmware development.
- Microcontrollers
- IoT devices
- Low-memory hardware
Variant Data Storage
When a variable holds different data types over time.
Example scenarios:
- Sensor readings
- Status flags
- Error codes
Hardware-Level Programming
Unions are common in system-level development.
Used in:
- Device drivers
- Register mapping
- Kernel programming
Binary Data Interpretation
Useful when interpreting raw binary memory differently.
Examples include:
- File parsing
- Network packets
When NOT to Use Unions
Avoid unions in general-purpose applications. They are not suitable for everyday programming tasks.
Do not use unions when:
- Multiple values must exist simultaneously
- Data safety is critical
- Code readability is important
- Beginners are still learning basics
In such cases, structures are safer.
Limitations of Union in C Language
Despite advantages, unions have important limitations.
- Single Active Member
Only one member can hold valid data at once.
- Data Overwriting Risk
New assignments destroy previously stored values.
- Debugging Complexity
Overlapping memory makes debugging slightly harder.
- Portability Issues
Memory alignment may differ across compilers. This matters in cross-platform development.
Real-World Applications
Unions are widely used in professional systems. However, they appear less in beginner programs.
Common applications include:
- Embedded firmware development
- Operating system internals
- Compiler design structures
- Network protocol handling
These areas require efficient memory management.
Common Mistakes Students Make
Beginners often misunderstand union behaviour.
Avoid these common errors.
- Treating union like structure
- Reading overwritten values
- Ignoring memory overlap
- Using unions unnecessarily
Understanding fundamentals prevents logical bugs later.
Conclusion
Union in C language demonstrates efficient memory sharing. It allows multiple variables to reuse the same memory space.
Although similar to structures in syntax, behaviour differs greatly. Unions are powerful but must be used carefully.
They are especially useful in embedded systems and low-level programming. Understanding unions strengthens your grasp of memory concepts in C.
If you want deeper mastery, learn unions alongside:
Together, these topics build strong programming fundamentals.
FAQs
What is a union in C language?
A union is a data type where all members share memory.
Structures allocate separate memory. Unions share one memory block.
No. Only the most recently assigned member remains valid.
They are mainly used for memory optimization and low-level programming.
Yes. Union vs structure is a frequently asked question. Mostly asked in BCA, MCA and Engineering Examinations.
More on Union in C Please click the Link
