New course! Every coder should learn Generative AI!
Try a free lesson+ 4
Tagged unions are not uncommon. Something like
struct {
int choice;
union {
char thing;
int thing2;
double thing3;
...
} value;
}
It's a union but you also "remember" what value you picked.
So a struct represents a combination of values, and a (tagged) union represents choice.
Imagine you are programming a calculator and you can either input whole numbers or fractions or decimal numbers.
You can store them all in a single tagged union type, which makes processing easier.
+ 2
Union are useful when memory footprint is a major issue.
By reusing the same variable for different usages throughout your code, you avoid having to allocate/use more memory.
About being overwritten, the assumption is that you will never user multiple types of an union at the same time