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 :
enum { charArr_type, float_type, int_type } VALUE_TYPE;
typedef union
{
char charArr[SIZE];
int intVal;
float floatVal;
} VALUE;
struct my_value {
VALUE val,
VALUE_TYPE val_type
}
After, you'll just have to update type when you assign your struct :
my_value number;
number.val.intVal = 8;
number.val.val_type = is_int
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.
No, you cannot tell, the language has no facility for that.
You have to keep track of that yourself if you need that information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With