Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine what type is used in a union?

Tags:

c

types

unions

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?

like image 909
ihatetoregister Avatar asked Feb 28 '12 09:02

ihatetoregister


2 Answers

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.

like image 108
Coren Avatar answered Oct 16 '22 08:10

Coren


No, you cannot tell, the language has no facility for that.

You have to keep track of that yourself if you need that information.

like image 30
Mat Avatar answered Oct 16 '22 08:10

Mat