UNIONS:
Unions are same as structures in some aspects i.e.,
union is also a collection of different datatypes of elements stored under a
single name but the major difference between union and structure is in terms of
their storage.
In
structure, each member has its own storage location where as in a union all the
members use the same location.
All the
members of the structure can be initialized at the same time but a union can
handle only one member at a time. Since, the members of the union share the
same memory.
Declaration
of a union is same as that of structure declaration except that the keyword
used is union.
Syntax:-
union tagname
{
datatype member 1;
datatype member 2;
:
datatype member n;
};
Eg.,
union student
{
int rollno;
float avg;
}s1;
The storage is allocated for the
member which occupies largest memory. Here,
the union contains two datatypes int and float. Since, the largest is float and
it occupies 4 bytes, s1 is allocated 4 bytes.
No comments:
Post a Comment