Alex D.
Alex D.

Reputation: 437

Union tested for current member in use

Do unions have a control structure to test which member is currently in use (or if it has any at all)? I'm asking this because undefined behavior is never a good thing to have in your program.

Upvotes: 11

Views: 4325

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258618

No, no such mechanism exists off-the-shelf. You'll have to take care of that yourself. The usual approach is wrapping the union in a struct:

struct MyUnion
{
   int whichMember;
   union {
      //whatever
   } actualUnion;
};

So you have MyUnion x; and x.whichMember tells you which field of x.actualUnion is in use (you have to implement the functionality though).

Upvotes: 14

Related Questions