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?
Is there any better solution?
No, the solution that you showed is the best (and the only) one. union
s 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.