è Structure data type is
so defined that is able to accept heterogeneous(mixed) data types. A union is
also similar to structure. union is a variable which may hold objects of
different data types and size.
è The important
difference between structure and union is that structure is a group of variable
of different types, while union is a single variable whose type is varying
among the type defined as members of union . Union variable is allocated the
memory of the largest type and then compiler keeps track of size and alignment
according to the last value of
particular data type.
è
union can be created
as follows:
union tag_name
{
type
member1
type
member2
.....
.....
}
Here, the keyword union
is used to create union. The tag_name specifies the name of union.
member1,member2 ... specifies the union member of particular type.
Ex, union data
{
char ch;
int i;
float f;
}u;
In above example the
union name is data which contains three members of character type, integer type
and float type.
The u is the variable
whose type can be character, integer or float but at a time any one only. The
largest type is float and hence memory allocated to union variable u is equal
to size of float.
The member of a union
data type shares a same memory. An union member accessed using . dot operator such as
union_var_name.member name
Ex;
u.i=10;
printf(“\n i= %d”,u.i);
Here, the value stored
in union is of integer type hence the access must be of type integer.when try
to print u.c or u.f , response is garbage.If use
u.f=10.5;
here, it overwrites the
previous integer .As last storage is of float the access should be of type
float only.