Union

UNION

A union is a special data type available in C that allows us to store different data types in the same memory location. We can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple-purpose.

DEFINING UNION
The union statement defines a new data type with more than one member for your program.
union [union tag]
{
member;
member;
..
..
member;
}

EXAMPLE:-
#include<stdio.h>
#inlcude<string.h>
union demo
{
int i;
char ch[2];
};
union demo a;
a.i=512;
printf("a.i=%d\n", a.i);
printf("a.ch[0]=%d\n", a.ch[0]);
printf("a.ch[1]=%d", a.ch[1]);

OUTPUT:-
a.i=512
a.ch[0]=0
a.ch[1]=2

ACCESSING UNION MEMBERS
To access any member of a union, we use the member access operator(.). The member access operator is coded as a period between the union variable name and the union member that we wish to access. We should use the keyword union to define the variables of union type.

Considering the above example, where a structure would have employed a total of four bytes for a.i and a.ch[], the union engages only two bytes. The same two bytes comprising a.i also comprises a.ch[]. Hence we can access the two bytes together by mentioning a.i, or individually by mentioning a.ch[0] and a.ch[1].

Post a Comment

0 Comments