Unions
are similar to structure. Its syntax and use is similar to structure. It also contains
members whose individual data types may differ from one another. The
distinction is that all members within union share the same storage area of
computer memory, whereas each member within a structure is assigned its own
unique storage. Thus, unions are used to conserve memory. Since same memory is
shared by all members, one variable can reside into memory at a time. When
another variable is set into memory, the previous is replaced i.e. previous can
not persist. Thus, unions are useful for applications involving multiple
members where values need to be assigned to all of the members at any one time.
Therefore, although a union may contain many members of different types, it can
handle only one member at a time.
The compiler allocates a piece of
storage that is large enough to hold the largest variable type in the union.
For example
The union is created as
union student
{
int roll;
float marks;
} ;
Here, the union student has members
roll and marks. The data type of roll is integer which contains 2 bytes in
memory and the data type of marks is float which contains 4 bytes in memory. As
all union members share same memory, the compiler allocates larger memory (i.e.
4 bytes in this case).
The declaration of union and its
variable is similar to that of structure. The union variable can be passed to
function and it can be member of any other structure. The union can be
illustrated as following examples;
Example:
Create an union named student that
has roll and marks as member. Assign some values to these members one at a time
and display the result one at a time.
void main()
{
union student
{
int roll;
float marks;
};
union student st;
st.roll=455;
printf("\nRoll=%d",st.roll);
st.marks=78;
printf("\nMarks=\t%f",st.marks);
}
output:
Roll=455
Marks= 78.000000
If two members are used
simultaneously, the output is unexpected as following
void main()
{
union student
{
int roll;
float marks;
};
union student st;
st.roll=455;
st.marks=78;
printf("\nRoll=%d",st.roll);
printf("\nMarks=\t%f",st.marks);
}
output:
Roll=0
Marks= 78.000000
Comments
Post a Comment