Unrestricted unions

Interview questions are like memes. Recently on the technical interview circuit, the question "How does one programmatically determine endian-ness?" has been making the rounds. The value of such a question is frequently debated, but it involves today's topic, the stepchild of data structures, the union.

One answer to the question can be put this way:

union X {
  char c;
  int i;
  X(void) : i(1) { };
  bool isBig(void) { return !!c; }; 
} x;
 ..
cerr << (x.isBig() ? "big" : "little");

The standard describes the union as being like the struct with the exception that "at most one non-static data member is active at a time," a description that strikes me as more circuitous than simply saying all ordinary members are at the same address.(**) There is the further restriction that members of the union must have only trivial constructors(++); the implication is that you may not have a member that is a user defined type that requires the constructor to have parameters.

The proffered reason was an insurance policy that the union's contents were well formed. But let's ask ourselves: "When you are not being being asked interview brainteasers, how often outside the hardware/firmware environment do you use the union?"

The change to the C++11 standard loosened the safety belts and discarded the airbags. With the exclusion of reference types (a reference has no address, much less the same one as another object in the program), you may now toss in whatever you like.

(**) It is really easy to overlook the soon-to-be-interview-circuit-brainteaser that unions may have an unlimited number of arbitrarily complex static members each of which most definitely has its own unique address. File this under ...

(++) The standard used to say that they "may not have non-trivial" constructors, which similarly is a circuitous, double negation near-pleonasm.

 

Last updated 2014-07-19T15:44:11+00:00.

Links to the standard

Section 9.5 covers the union, but search on the phrase "variant members" to find the places in sections 12 and 15 where there are changes regarding member functions.

Benefits

If you know what you are doing and why you are doing it, the broader definition of union membership may be useful.

Risks

Unions could always be risky. They still are.