Unions in C
A union in C is a user-defined data type, similar to structures, but with one key difference: all members of a union share the same memory location. This means that a union can store different data types, but only one member can hold a value at a time. The size of the union is determined by its largest member, and changing the value of one member will overwrite the value of other members.
At SamagraCS Educational Technology, we aim to make learning about unions easy by breaking down the concept into simple steps, with practical examples and real-life analogies.
What is a Union?
A union is a special data type in C that allows you to store different data types in the same memory location. It’s useful when you need to save memory by not using more memory than necessary to store a value.
Real-Life Analogy:
Imagine you have a single locker, but you can only store one item at a time in it. You can keep a book, a laptop, or a bag in the locker, but only one item can be stored at any given time. Similarly, in a union, only one member can hold a value at a time.
Defining a Union
Just like a structure, you define a union using the union
keyword, but all members of the union share the same memory space.
Syntax:
union union_name {
data_type1 member1;
data_type2 member2;
// More members
};
- union_name: The name you give to the union.
- data_type1, data_type2: Data types for each member of the union (e.g.,
int
,float
,char[]
). - member1, member2: Names of the union members.
Example of Defining a Union
Let’s define a union that can store an integer, a float, or a string.
#include <stdio.h>
union Data {
int i;
float f;
char str[20];
};
int main() {
union Data data;
// Assigning values to union members
data.i = 10;
printf("Integer: %d\n", data.i);
data.f = 220.5;
printf("Float: %.2f\n", data.f);
strcpy(data.str, "SamagraCS");
printf("String: %s\n", data.str);
return 0;
}
Output:
Integer: 10
Float: 220.50
String: SamagraCS
Explanation:
- Union Definition:
- The union
Data
can store an integer (i
), a float (f
), or a string (str
).
- Assigning Values:
- We assign values to different members of the union one by one. Each time a value is assigned to a member, it overwrites the previous value because all members share the same memory location.
- Output:
- Only the most recent value assigned to the union is valid. After assigning a string to
data.str
, the previous values ofdata.i
anddata.f
are no longer valid.
Key Difference Between Structure and Union
Feature | Structure | Union |
---|---|---|
Memory Allocation | Each member gets its own memory space. | All members share the same memory space. |
Size | Size is the sum of the sizes of all members. | Size is the size of the largest member. |
Access | All members can hold values simultaneously. | Only one member can hold a value at a time. |
Memory Allocation in Unions
The size of a union is equal to the size of its largest member. This is because all members share the same memory location, and the union must be large enough to hold the largest member.
Example:
#include <stdio.h>
union Data {
int i;
float f;
char str[20];
};
int main() {
union Data data;
printf("Size of union: %lu\n", sizeof(data)); // Output the size of the union
return 0;
}
Output:
Size of union: 20
In this case, the size of the union is 20
bytes, which is the size of the largest member (str
), even though int
and float
are smaller.
Real-Life Example: Storing Employee Information
Let’s say we want to store information about an employee. An employee can either have an ID number, a salary, or a department name. Using a union can help save memory when only one of these values is needed at a time.
Code Example:
#include <stdio.h>
union EmployeeInfo {
int id;
float salary;
char department[20];
};
int main() {
union EmployeeInfo emp;
// Storing the employee's ID
emp.id = 101;
printf("Employee ID: %d\n", emp.id);
// Storing the employee's salary
emp.salary = 55000.75;
printf("Employee Salary: %.2f\n", emp.salary);
// Storing the employee's department
strcpy(emp.department, "HR");
printf("Employee Department: %s\n", emp.department);
return 0;
}
Output:
Employee ID: 101
Employee Salary: 55000.75
Employee Department: HR
In this example, the employee’s ID, salary, and department are stored in the same memory location. Only the most recently assigned value is valid.
Advantages of Using Unions
- Memory Efficiency: Since all members share the same memory location, a union uses less memory than a structure.
- Flexibility: A union allows you to store different data types in the same memory location, but only one at a time. This is useful when you need to work with multiple types of data but only one type will be active at a time.
Disadvantages of Using Unions
- One Value at a Time: You can only store one value at a time. Assigning a new value to a different member overwrites the previous value.
- Data Corruption: Accessing a member after a different member has been assigned can lead to undefined behavior since the memory is shared.
When to Use Unions?
- Unions are ideal when you need to handle multiple data types, but only one at a time, and want to save memory. For example:
- I/O Handling: Handling different data types coming from a file or network.
- Embedded Systems: Where memory is limited, and unions can help reduce memory usage.
Conclusion
A union in C is a powerful tool that allows you to store different types of data in the same memory location, but only one at a time. It’s especially useful when memory efficiency is important, such as in embedded systems or when working with low-level hardware.
At SamagraCS Educational Technology, we believe that understanding concepts like unions will help you become a more efficient programmer. Practice using unions in different scenarios to see how they can optimize your programs.
For any questions, feel free to reach out to Pawan & Pooja , or the team at SamagraCS Educational Technology! Happy coding!