C UNION


Unions are mainly used to conserve memory. Unions are a special form of Structures. Unions also follow the same syntax as structures. The major distinction between them is in the terms of storage. Unions are mainly used to conserve memory. In structures, each member has its own storage location, whereas all the members of a union use the same location. Though unions may contain many members of different types, it can handle only one member at a time. Unions are useful in applications involving multiple members where values are not assigned to all the members at any one time.

Unions can be declared using the keyword union as follows:

union tag
{
  member1;
  member 2;
  - - -
  member m;
};


Where union is a required keyword and the other terms have the same meaning as in a structure definition.

Individual union variables can then be declared as
union tag variable1,variable2, -----, variable n;
where union is a required keyword, tag is the name that appeared in the union definition and variable 1, variable 2, variable n are union variables of type tag.

The two declarations may be combined, just as we did in the case of structure. Thus, we can write.

union tag
{
  member1;
  member 2;
  - - -
  member m;
} variable 1, varibale2. . . variable n;


The tag is optional in this type of declaration.
For example consider the following declaration of union:

union code
{
  char color [5];
  int size ;
}purse, belt;


Here we have two union variables, purse and belt, of type code. Each variable can represent either a 5–character string (color) or an integer quantity (size) of any one time.

Consider another example :

union item
{
  int m;
  float x;
  char c;
}code;

This declares a variable of type union item. The union contains three members, each with a different data type. However, we can use only one of them at a time. This is due to the fact that only one location is allocated for a union variable, irrespective of size. The compiler allocates a piece of storage that is large enough to hold the largest variable type in the union. In the declaration above the member x requires 4 bytes which is the largest among the members.
In short, structures occupy the memory which is the sum total of memory occupied by all the members in it whereas a union occupies the memory equal to the memory of the largest variable type.
To access a union member, we can use the same syntax that we can use for structure members. That is,
code.m
code.x
code.c
During accessing, we should make sure that we are accessing the member whose value is currently stored.
For example, the statements such as
code.m = 65;
code.x = 6651.38;
printf("%d".code.m);
The above would produce erroneous output(which is machine dependent);

Copyright © 2018-2020 TutorialToUs. All rights reserved.