Loading, please wait...

Initialization

In a declaration, a union may be initialized with a value of the same type as the first union member.

 

For example, with the preceding union, the declaration

union number value = { 10 };

is a valid initialization of union variable value because the union is initialized with an int, but the following declaration would truncate the floating-point part of the initializer value and normally would produce a warning from the compiler:

union number value = { 1.43 };

Comparing unions is a syntax error. The amount of storage required to store a union is implementation dependent but will always be at least as large as the largest member of the union.

 

 

Demonstrating Unions

The program uses the variable value of type union number to display the value stored in the union as both an int and a double. The program output is implementation dependent. The program output shows that the internal representation of a double value can be quite different from the representation of it.

 

Example

/*A C program for union*/
#include <stdio.h>
.
/* number union definition */
union number {
int x;
double y;
};

Int main( void )
{
union number value; /* define union variable */

x = 100; /* put an integer into the union */
printf( "%s\n%s\n%s\n %d\n\n%s\n %f\n\n\n",
"Put a value in the integer member",
"and print both members.",
"int:", value.x,
"double:", value.y );

y = 100.0; /* put a double into the same union */
printf( "%s\n%s\n%s\n %d\n\n%s\n %f\n",
"Put a value in the floating member",
"and print both members.",
"int:", value.x,
"double:", value.y );

return 0;
}

Output:

Put a value in the integer member and print both members.

int:

100

double:

-92559592117433136000000000000000000000000000000000000000000000.000000


Put a value in the floating member

and print both members.

int:

0


double:

100.000000