Unions in C
A union in C is a special data type that allows multiple members to share the same memory location.
Unlike structures, where every member has its own memory, union members overlap in memory — only one value can exist at a time.
What is a Union?
A union is a user-defined datatype similar to a structure but with one key difference: All members share the same memory.
- Only one member stores a valid value at a time
- Memory = size of the largest member
- Efficient memory usage
- Useful for embedded systems, hardware-level programming
Syntax of Union
union UnionName {
data_type member1;
data_type member2;
...
};
Union vs Structure
- Structure → Each member has its own memory
- Union → All members share one memory block
- Union size = largest member only
- Structure size = sum of members
Unions save memory — best for programs dealing with multiple data formats stored at different times.
Where Unions Are Used?
- Interpreting same memory in different ways
- Embedded systems memory optimization
- Handling different data formats
- Device drivers
- Networking (protocol parsers)
5 Practical Examples of Unions
Example 1 – Basic Union Usage
#include <stdio.h>
union Data {
int i;
float f;
};
int main() {
union Data d;
d.i = 10;
printf("Int: %d\n", d.i);
d.f = 3.14;
printf("Float: %.2f", d.f);
return 0;
}
Example 2 – Only Latest Value Survives
#include <stdio.h>
union Example {
int x;
char y;
};
int main() {
union Example e;
e.x = 100;
e.y = 'A';
printf("Integer (corrupted): %d\n", e.x);
printf("Char: %c", e.y);
return 0;
}
Example 3 – Union Size
#include <stdio.h>
union Test {
int a;
double b;
char c;
};
int main() {
printf("Size = %lu bytes", sizeof(union Test));
return 0;
}
Example 4 – Using Union for Different Formats
#include <stdio.h>
union Number {
int integer;
float decimal;
};
int main() {
union Number n;
n.integer = 500;
printf("Integer: %d\n", n.integer);
n.decimal = 10.75;
printf("Decimal: %.2f", n.decimal);
return 0;
}
Example 5 – Union Inside Structure
#include <stdio.h>
struct Student {
char name[20];
union {
int roll;
float percentage;
} info;
};
int main() {
struct Student s = {"Sourav"};
s.info.roll = 101;
printf("Name: %s\nRoll: %d", s.name, s.info.roll);
return 0;
}
Practice Questions
- What is a union? How is it different from a structure?
- Explain memory allocation in unions.
- Why can a union store only one value at a time?
- Give real-life applications of unions.
- Create a union to store integer, float, and char values.
Practice Task:
Create a program using a union to store temperature readings in both Celsius and Fahrenheit.
Show how assigning one value overwrites the other.