UNIONS

·

Unions, like structure contain members, whose individual data types may vary. This is a is major distinction between them in terms of storage .In structures each member has its own storage location, where as all the members of a union use the same location.

Like structures, a union can be declared using the keyword union is follows:
union item
{
int m;
float x;
char c;
} code;

This declares a variable code of type union item. The union contains item members, each with a different date 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 its 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. The above figure shown how all the three variables share the same address, this assumes that a float variable requires 4 bytes of storage.

To access a union member, we can use the same syntax that we as for structure members, that is:-
code. m
code. x
code. c
are all valid
When accessing member variables, we should make sure that we are accessing the member whose value is currently in storage. For example
code. m = 565;
code. x = 783.65;
printf(“%d”, code. m);
would produce erroneous output.

# include "stdio.h"
main( )
{
union
{
int one;
char two;
} val;
val. one = 300;
printf(“val. one = %d \n”, val. one);
printf(“val. two = %d \n”, val. two);
}

The format of union is similar to structure, with the only difference in the keyword used.
The above example, we have 2 members int one and char two we have then initialised the member ‘one’ to 300. Here we have initialised only one member of the union. Using two printf statements, then we are displaying the individual members of the union val as:
val. one = 300
val. two = 44
As we have not initialised the char variable two, the second printf statement will give a random value of 44.

The general formats of a union thus, can be shown as.
union tag {
member 1;
member 2;
- - -
- - -
member m;
};

The general format for defining individual union variables:
Storage-class Union tag variable 1, variable 2,........., variable n;
Storage-class and tag are optional variable 1, variable 2 etc, are union variable of type tag.
Declaring union and defining variables can be done at the same time as shown below:

Stroage-calss union tag {
member 1;
member 2;
- - -
- - -
- - -
member m;

} variable 1, variable 2, - - - , variable n;

About Me

Blog Archive