11

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.

Alex D.
  • 427
  • 1
  • 5
  • 14

1 Answers1

14

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).

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • 3
    +1: This type of structure is often called either a "discriminated union" or a "tagged union". – John Dibling Jun 14 '12 at 14:45
  • 1
    Yes, I thought of a similar approach, but because I prefer language constructs to self-made ones I just had to know if one existed. Thanks for the quick answer. – Alex D. Jun 14 '12 at 15:17
  • @AlexD. Pascal had a tagged union, but it amounted to the same thing as this. You still had to test the tag to determine which element was in use. – Spencer Nov 19 '21 at 17:26