Is it possible to determine what type a union contain if there are several possible choices?
typedef union
{
char charArr[SIZE];
int intVal;
float floatVal;
} VALUE_TYPE;
VALUE_TYPE number;
number.intVal = 8;
How to know what the union contain here if the value was set from somewhere else?
It’s right that you cannot do this kind of thing out of the box.
A common way to workaround this is that you can add a type along with your union. For instance, it could be :
After, you’ll just have to update type when you assign your struct :
It’s a common modern pattern when you need to have a common type capable of storing nearly anything.
For instance, you can found it everywhere in PHP source code. This is how they store different value types in the same object. See this page for more detail.