C – Union 2017-08-07T14:12:07+00:00

# Union :

Union is a data type with two or more member similar to structure but in this case all the members share a common memory location. The size of the union corresponds to the length of the largest member. Since the member share a common location they have the same starting address.

The real purpose of unions is to prevent memory fragmentation by arranging for a standard size for data in the memory. By having a standard data size we can guarantee that any hole left when dynamically allocated memory is freed will always be reusable by another instance of the same type of union. This is a natural strategy in system programming where many instances of different kinds of variables with a related purpose and stored dynamically.

A union is declared in the same way as a structure.The syntax of union declaration is
union union_name
{
type element 1;
type element 2;
……………..
type element n;
};
This declares a type template. Variables are then declared as:
union union_name x,y,z;

For example, the following code declares a union data type called Student and a union variable called stud:
union student
{
int rollno;
float totalmark;
};
union student stud;

It is possible to combine the declaration of union combination with that of the union variables, as shown below.
union union_name
{
type element 1;
type element 2;
……………..
type element n;
}var1,var2,…,varn;

The following single declaration is equivalent to the two declaration presented in the previous example.
union student
{
int rollno;
float totalmark;
}x,y,z;

Exercise: Compare structure and Union

Structure:

Output :

 sizeof(var)=7 sizeof (var.a)=2 sizeof (var.b)=1 sizeof (var.c)=4 10 W 10 W 3.140000

Union :

Output :

 sizeof(var)=4 sizeof (var.a)=2 sizeof (var.b)=1 sizeof (var.c)=4 10 W -2621 1- 3.140000