1. Introduction
Union is basic C data type. Like structure it also had data members. Then how it differs from the structure. If a structure has 10 data members space is allocated for all data members. But, in case of the union, the compiler looks for the largest data member in the union and allocates the space for it. The union member can be accessed the same way the structure member is accessed using the period operator.
2. Declaration
Below is the declaration for the sample union data type:
union Department
{
int deptid;
long numberofEmp;
float total_salary_expense;
};
In the above declaration, the union is named as Department. And it has three data members. So the size allocated for the union is size of the float as it consumes more bits for its storage.
So, if union allocates storage for the largest member, Is it possible to assign and retrieve value for all the member one at a time? No. That is the answer. Because the values are overwritten.
3. An Example
Consider the below example:
#include "stdafx.h"
#include "conio.h"
union Department
{
int deptid;
long numberofEmp;
float total_salary_expense;
};
int _tmain(int argc, _TCHAR* argv[])
{
union Department dept;
dept.deptid = 100;
printf("Dept id = %d \n", dept.deptid );
dept.numberofEmp = 15000;
printf("Total Employee = %ld \n", dept.numberofEmp );
printf("Try to Print Dept Id = %d", dept.deptid );
getch();
return 0;
}
When we run the example, we will get the following result:
Even though we accessed the DeptId we got 15000 as the value in the last line of the output. So as there is only a single storage (The storage required for the largest among the member) and it shared by all three, we got 15000 for dept id in the last line.