C-Unions

Union:

Unions like structure contain members whose individual data types may differ from one another. However the members that compose a union all share the same storage area within the computers memory where as each member within a structure is assigned its own unique storage area. Thus unions are used to observe memory. They are useful for application involving multiple members. Where values need not be assigned to all the members at any one time. Like structures union can be declared using the keyword union as follows:

union item
{
int m;
float p;
char c;
}
code;

A union is data type where the data area is shared by two or more members generally of different type at different times.

For Example :-

union u_tag {

            short ival ;

            float fval ;

            char cval ;

            } uval ;

The size of uval will be the size required to store the largest single member, 4 bytes in this case to accommodate the floating point member.

Example :-

union conversion {

unsigned short num ;

struct status bits ;

} number ;

We can load number with an integer

scanf( “%u”, &number.num );

error: Content is protected !!