Unions

Structures are a way of grouping homogeneous data together. But it often happens that at any time we require only one of the member’s data. For example, in case of the support price of shares you require only the latest quotations. And only the ones that have changed need to be stored. So if we declare a structure for all the scripts, it will only lead to crowding of the memory space. Hence it is beneficial if we allocate space to only one of the members. This is achieved with the concepts of the UNIONS.

UNIONS are similar to STRUCTURES in all respects but differ in the concept of storage space.

A UNION is declared and used in the same way as the structures. Yet another difference is that only one of its members can be used at any given time. Since all members of a Union occupy the same memory and storage space, the space allocated is equal to the largest data member of the Union. Hence, the member which has been updated last is available at any given time.

For example a union can be declared using the syntax shown below:

union union-tag {
datatype variable1;
datatype variable2;

};

For example,

union temp
{
int x;
char y;
float z;
};

In this case a float is the member which requires the largest space to store its value hence the space required for float (4 bytes) is allocated to the union. All members share the same space. Let us see how to access the members of the union.

Write a program to illustrate the concept of union.

/* Declare a union template called tag */
union tag {
int nbr;
char character;
}
/* Use the union template */
union tag mixed_variable;
/* Declare a union and instance together */
union generic_type_tag {
char c;
int i;
float f;
double d;
} generic;

 

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: