C'Language - [Union/Structure]

♠ Posted by Unknown in at 01:15

Union:

Unions are also derived data type like structures. The concept of union is borrowed from structures and hence we define and declare a union exactly like a structure with the exception that we use the reserved word union in place of struct.

Syntax:

union <name of union>
{
 <type specifier> <variable1>;
 <type specifier> <variable2>;

 <type specifier> <variablen>;
};

In a structure each member has a storage location once it is associated with the structure, but in all a union, all the members use the same location. Structure and union with respect to storage of members and that is, the storage location allocated to a structure is the total of the storage location needed to store all the members of a structure, whereas in the union, the storage size is equal to the size of the largest member of the union.

Example:

union test
{
 int rno;
 char name[20];
 int fees;
};

Structure v/s Union

Both structure and union are derived data types, and follow the same concept, there one major fundamental difference between the two.

The difference is that, in a structure each member has a storage location once it is associated with the structure, but in a union, all the members use the same location. This means that, even though a union can contain members of different data types, it can only handle only one member at a time.

There is difference between structure and union with respect to storage of members and that is, the storage location allocated to a structure is the sum total of the storage location needed to store all the members of the array, whereas in the union, the storage size is equal to the size of the largest member of the union.

0 comments:

Post a Comment