How to check what type is currently used in union?

tomdavies picture tomdavies · May 18, 2013 · Viewed 12.2k times · Source

let's say we have a union:

typedef union someunion {
    int a;
    double b;
} myunion;

Is it possible to check what type is in union after I set e.g. a=123? My approach is to add this union to some structure and set uniontype to 1 when it's int and 2 when it's double.

typedef struct somestruct {
    int uniontype
    myunion numbers;
} mystruct;

Is there any better solution?

Answer

Sergey Kalinichenko picture Sergey Kalinichenko · May 18, 2013

Is there any better solution?

No, the solution that you showed is the best (and the only) one. unions are pretty simplistic - they do not "track" what you've assigned to what. All they do is let you reuse the same memory range for all their members. They do not provide anything else beyond that, so enclosing them in a struct and using a "type" field for tracking is precisely the correct thing to do.