Unions are class types that can contain only one data element at a time (although the data element can be an array or a class type). The members of a union represent the kinds of data the union can contain. An object of union type requires enough storage to hold the largest member in its member-list. Consider the following example:
#include <stdlib.h>
#include <string.h>
#include <limits.h>
union NumericType // Declare a union that can hold the following:
{
int iValue; // int value
long lValue; // long value
double dValue; // double value
};
void main( int argc, char *argv[] )
{
NumericType *Values = new NumericType[argc - 1];
for( int i = 1; i < argc; ++i )
if( strchr( argv[i], '.' ) != 0 )
// Floating type. Use dValue member for assignment.
Values[i].dValue = atof( argv[i] );
else
// Not a floating type.
{
// If data is bigger than largest int, store it in
// lValue member.
if( atol( argv[i] ) > INT_MAX )
Values[i].lValue = atol( argv[i] );
else
// Otherwise, store it in iValue member.
Values[i].iValue = atoi( argv[i] );
}
}
The NumericType
union is arranged in memory (conceptually) as shown in Figure 8.1.
Figure 8.1 Storage of Data in NumericType Union