Export (0) Print
Expand All

Union (C++)

A user-defined data type or class type that, at any given time, contains only one object from its list of members. (However, that object can be an array or a class type.)

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

tag

The type name given to the union.

member-list

List of the types of data that the union can contain. See Remarks.

declarators

Declarator list that specifies the names of the union. For more information, see Overview of Declarators.

Union is a struct-like type that is provided in C and C++ to enable efficient use of memory. Both unions and structs assign values to members, and read from them, in the same manner. However, members of a struct occupy adjacent areas of memory, but members of a union share the same data space.

Use unions cautiously. Assigning a value to one union member also affects the other union members. A write to one member that is followed by a read from another member is sometimes, but not always, an implicit cast.

The member-list of a union represents the kinds of data that the union can contain. A union requires enough storage to hold the largest member in its member-list. For more information, see Union Declarations.

Declaring a Union

Begin the declaration of a union by using the union keyword, and enclose the member list in braces.

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

int main()
{
}

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 (these include constructors and destructors). It cannot contain virtual functions or static data members. It cannot be used as a base class, and it cannot 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 not required.

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 that is 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 braces. The expression is evaluated and assigned to the first field of the union.

// using_a_union.cpp
#include <stdio.h>

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

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

10
3.141600

The NumericType union is arranged in memory (conceptually) as shown in the following figure.

Storage of Data in NumericType Union

Numeric Type Union Data Storage

We recommend that you do not use a union to cast data from one data type to another because union members occupy the same address in memory.

There is no data-conversion support for unions. The results of interchanging writes and reads between union members of different types are unpredictable and depend on a variety of reasons.

The following example is a modified version of the previous example. In this version, the line that assigns the value 3.1416 to Values.dValue is commented out. This causes the code to try to print the value of an inactive member of the union (that is, a member that never receives an assignment). The member Values.iValue becomes active when it receives an assignment, and remains active when the code tries to print the value for Values.dValue. Because dValue and iValue are at the same location in memory, the second printf_s does not display the value 0.0 and the results are undefined instead.

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

The active member of a union is the one whose value was most recently set, and only that member has a valid value.

Community Additions

ADD
Show:
© 2014 Microsoft