Anonymous unions

One of the features of C++ is the ability to declare a union, without specifying a name. Here’s an example:

union {
   int a;
   char b;
};

(yes, they can be useful, and I’ll give an example shortly). The standard [class.union.anon / 12.3.1] states the following limitations:

  • Names of members of the anonymous union need to be distinct from any other in the scope of the declared union.
  • Each variable declared in the union will have the same address (C++14)
  • Anonymous unions can’t contain member functions
  • all members are public

The main effect is that the members of a union are defined in scope after the anonymous union is defined. The members may be referenced as though they were any other variable in scope. For example:

int c;
union {
   int a;
   char b;
};

a = 1;
c = 2;

Where it is useful

Tagged unions are an interesting use-case:

Class Tagged{
   union {
      int a;
      char b;
   };

   enum { INT_USED = 1,  CHAR_USED=2 } tag;
};
Continue readingAnonymous unions