/    /  Unions

Unions

 

A union is a special type of data available in C which enables the storage of different types of data in the same memory location. You can define a union with many members, but a single member can hold value at any time. Unions provide an effective means of using the same memory location for multiple purposes.

 

Defining a Union:

 

To define a union, you must use the union declaration in the same manner that you did when defining a structure. The union statement sets out a new type of data with more than one participant in your program. The form of the union declaration is as follows:

 

union [union tag] {
 member definition;
 member definition;
 ...
 member definition;
} [one or more union variables];

 

The union label is optional and every definition of membership is a definition of a normal variable, int i; or float f; or another valid variable definition.

At the end of the union definition, before the final semi-colon, you can specify one or several union variables, but this is optional. Here’s how you would define a trade union type named Data with three members i, f, and str-

 

union Data {
int i;
float f;
char str[20];
} d;

 

A variable of ‘d’ type can store an integer, a floating-point number, or a string. This means that a single variable, the same storage location, can be used to store multiple types of data. You can use any type of inbuilt or user-defined data within a union based on your needs.

The memory occupied by a union must be sufficient to contain the largest member of the union. For example, in the above example, the data type will take up 20 bytes of memory space as this is the maximum space that can be occupied by a string.

 

Example Program:

 

To display the total memory size occupied by the above union.

 

#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data d;
printf( "Memory size occupied by data : %d\n", sizeof(d));
return 0;
}

 

Output:

 

unions