Unions

union [tag] { member-list } [declarators];

[union] tag declarators;

A union is a user-defined data or class type that, at any given time, contains only one object from its list of members (although that object can be an array or a class type). The member-list of a union represents the kinds of data the union can contain. A union requires enough storage to hold the largest member in its member-list. See Union Declarations (C Language Reference).

Declaring a Union

Begin the declaration of a union with the union keyword, and enclose the member list in curly braces:

union DATATYPE    // Declare union type
{
   char   ch;
   int    i;
   long   l;
   float  f;
   double d;
} var1;          // Optional declaration of union variable

Using a Union

A C++ union is a limited form of the class type. It can contain access specifiers (public, protected, private), member data, and member functions, including constructors and destructors. It cannot contain virtual functions or static data members. It cannot be used as a base class, nor can it have base classes. Default access of members in a union is public.

A C union type can contain only data members.

In C, you must use the union keyword to declare a union variable. In C++, the union keyword is unnecessary:

union DATATYPE var2;   // C declaration of a union variable
DATATYPE var3;         // C++ declaration of a union variable

A variable of a union type can hold one value of any type declared in the union. Use the member-selection operator (.) to access a member of a union:

var1.i = 6;           // Use variable as integer
var2.d = 5.327;       // Use variable as double

You can declare and initialize a union in the same statement by assigning an expression enclosed in curly braces. The expression is evaluated and assigned to the first field of the union. For example:

#include <stdio.h>

union NumericType
{
   int      iValue;
  long        lValue;
   double      dValue;
};

void main()
{
   union NumericType Values = { 10 };  // iValue = 10
  printf("\n%d", Values.iValue);
  Values.dValue = 3.1416;
  printf("\n%f", Values.dValue);
}

The NumericType union is arranged in memory (conceptually) as shown in Figure 8.1.

Figure 8.1   Storage of Data in NumericType Union

See Also

Anonymous Unions, class, struct, Classes, Structures, and Unions