Anonymous unions

An anonymous union is a union without a name. It cannot be followed by a declarator. An anonymous union is not a type; it defines an unnamed object.

The member names of an anonymous union must be distinct from other names within the scope in which the union is declared. You can use member names directly in the union scope without any additional member access syntax.

For example, in the following code fragment, you can access the data members i and cptr directly because they are in the scope containing the anonymous union. Because i and cptr are union members and have the same address, you should only use one of them at a time. The assignment to the member cptr will change the value of the member i.

      void f()
      {
      union { int i; char* cptr ; };
      /* . . .  */
      i = 5;
      cptr = "string_in_union"; // overrides the value 5
      }

C++ An anonymous union cannot have protected or private members, and it cannot have member functions. A global or namespace anonymous union must be declared with the keyword static.

Related information



[ Top of Page | Previous Page | Next Page | Contents | Index ]