Union

Definition : The special data type allowing users to store different types of data in the same memory location is called union. These are user defined data type.

 

Declaring union in C

The keyword union is used for declaring union in the C program.
The following method is used to declare union:

union <union tag>
{
member definition;
member definition;
……..
……..
member definition;
} [one or more than one union variables];

The member definition can be any valid variable definition such as integer type (int) or float type etc.
The tag defined as union tag is optional. And the union variables defined after the closing of union bracket are also optional.

Example to show declaration of union in C

union Address
{
int num;
double d;
char ch[10];
} address;

From the above example we conclude that the variable of address type can store integer, double type values, and a sequence of characters in the same memory location. Hence, a single data type is used here to store multiple types of data.
Apart from inbuilt data types (int, double, char) you can also store user defined data types in the union statement as per your requirement.

 

Allocation of memory by union

The union when defined in a C program takes the size of its largest member.

For example:

#include <stdio.h>

union Compute
{
int i;
float f;
char ch[20];
};
int main( )
{
union Compute compute;
printf( “ Memory address occupied by Compute : % d \n ” , sizeof(compute));
return 0;
}

Result of the above code:
Memory address occupied by Compute : 20

Hence, the union compute type will occupy the maximum space in memory which is 20 bytes as defined by the character string in the above mentioned program.

 

How to access members of union?

The members of union are accessed using the operator (.) and (->) similarly like structure.

Operator (.) : For accessing different members.
Operator (->) : For accessing pointer variables.

Example:
union Travel
{
char name[20];
int cost;
} travel1 , travel2, *travel3;

To access cost of travel1 and travel2, the operator (.) is used – travel1.cost, travel2.cost.

To access cost of *travel3, the operator -> is used – *travel3->cost.

Leave a Reply

Your email address will not be published. Required fields are marked *