How to check what type is currently used in union?

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.

Leave a Comment

tech