How to determine which type is used in a union?

Is it possible to determine which type contains a union if there are several possible options?

typedef union { char charArr[SIZE]; int intVal; float floatVal; } VALUE_TYPE; VALUE_TYPE number; number.intVal = 8; 

How do I know what the union contains if the value was set elsewhere?

+4
source share
3 answers

It is true that you cannot do such things out of the box.

A common way around this is that you can add a type along with your union. For example, 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 that, you just need to update the type when assigning your structure:

 my_value number; number.val.intVal = 8; number.val.val_type = is_int 

This is an ordinary modern template when you need to have a common type that can store almost everything.

For example, you can find it everywhere in the PHP source code. So they store different types of values ​​in the same object. See this page for more details.

+5
source

No, you cannot say, the language for this does not have.

You must follow this yourself if you need this information.

+1
source

Using the union, you need to keep track of what you have invested in it, and make sure that you return the correct type at the right time.

Do not use unions. Do you really have memory problems that require space savings?

0
source

Source: https://habr.com/ru/post/1398781/


All Articles