Unions In C Language
Unions:
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 :-
Syntax
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.
Union members are accessed in the same way as structure members and union pointers are valid.
CODE/PROGRAM/EXAMPLE
uval.ival = 10 ;
uval.cval = 'c' ;
When the union is accessed as a character we are only using the bottom byte of storage, when it is accessed as a short integer the bottom two bytes etc. It is up to the programmer to ensure that the element accessed contains a meaningful value.
A union might be used in conjunction with the bit-field struct status in the previous section to implement binary conversions in C.
For Example :-
Syntax
union conversion {
unsigned short num ;
struct status bits ;
} number ;
We can load number with an integer
CODE/PROGRAM/EXAMPLE
scanf( "%u", &number.num );
Since the integer and bit--field elements of the union share the same storage if we now access the union as the bit--field variable bits we can interpret the binary representation of num directly.
CODE/PROGRAM/EXAMPLE
i.e. if ( uvar.bits.bit15 )
putchar( '1' ) ;
else
putchar('0') ;
...
if ( uvar.bits.bit0 )
putchar( '1' ) ;
else
putchar('0') ;
Admittedly rather inefficient and inelegant but effective.