Union tested for current member in use

前端 未结 1 477
有刺的猬
有刺的猬 2021-01-05 01:08

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 h

相关标签:
1条回答
  • 2021-01-05 01:45

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

    0 讨论(0)
提交回复
热议问题