A union may be considered to be a class where the members are mutually exclusive alternatives to each other. Each member has zero offset and the union is large enough to hold the biggest member. At any given time, at most one of the members of the union is considered to be the active member. The following applies to unions.

Anonymous unions

A union of the form:

union { member_list };

is referred to as an anonymous union. Such a union has no tag name and declares no instances. Within its scope of declaration, the names of the members of an anonymous union must not conflict with other names. This is because the members are directly accessible to the containing scope and the usual member access syntax is not required. There are two conditions that apply to anonymous unions:


Following is an example of an anonymous union.

 union {int i; double n;}; // No tag name and no instance, therefore anonymous.
 i = 0;                    // Available without member access operator.
 n = 2.0;                  // Overwrites value of i by assigning to n.

If an instance of the above union is declared (still with no tag name), the union is no longer treated as anonymous, as described below.

 union {int i; double n;} u; // No tag name but has an instance u.
 i = 0;                      // Syntax Error !!
 u.i = 0;                    // This is correct.