In this lesson, you will learn about the data union in C, its usage, along with examples to better understand the topic.
What are unions in C?
A union in C is a particular data type that allows storing different data types in the same memory location. A union is similar to a struct with few differences; a set of members with different data types grouped together under one entity. However, a struct allocates storage space to all its elements separately. In contrast, a union allocates shared storage space for all its elements. Also, in a struct, all elements’ values can be accessed simultaneously, while in a union, only one element can be accessed at a time.
Example of a union in C
#include <stdio.h>
#include <string.h>
union EmployeeInfo {
char name[30];
int id;
int age;
char department[20];
float salary;
};
int main() {
union EmployeeInfo employeeInfo1;
union EmployeeInfo employeeInfo2;
// asign values to union employeeInfo1
strcpy(employeeInfo1.name, "Fred");
employeeInfo1.id = 1;
employeeInfo1.age = 31;
strcpy(employeeInfo1.department, "Engineering");
employeeInfo1.salary = 5000.00;
printf("Union employeeInfo1 values:\n");
printf("Name: %s \n", employeeInfo1.name);
printf("ID: %d \n", employeeInfo1.id);
printf("Age: %d \n\n", employeeInfo1.age);
printf("Department: %s \n\n", employeeInfo1.department);
printf("Salary: %f \n\n", employeeInfo1.salary);
// asign values to union employeeInfo2
printf("Union employeeInfo2 values:\n");
strcpy(employeeInfo2.name, "Alex");
printf("Name: %s \n", employeeInfo2.name);
employeeInfo2.age = 28;
printf("Age: %d \n", employeeInfo2.age);
employeeInfo2.salary = 70000.00;
printf("salary: %f \n", employeeInfo2.salary);
return 0;
}
Output
Union employeeInfo1 values:
Name: FredID: 1
Age: 31
Department: Engineering
Salary: 5000.00Union employeeInfo2 values:
Name: Alex
Age: 28
salary: 70000.00
Point to remember
- A union allows to store different data types in the same memory location
- Unions are similar to structs with two differences.
- A union allocates shared storage space for all its elements, while a struct allocates storage space to all its elements separately.
- A union accesses only one element at a time, while a struct can access all elements’ values at the same time.
