Search code examples
cstructtypesunions

How do I easily access the active value of my union?


How can I access the active value of my union?

For example, if I have union like this:

typedef union               u_signed_identifier{
 char                       i_char;
 int                        i_int;
}                           t_signed_identifier;

I assign the value 14 to the int variable contained in my union:

t_signed_identifier example;
example.i_int = 14;

I would like to access that value without having to call my int variable.

For example:

printf("my value = %d\n", example);

This example displays a warning when I compile with gcc.

Is there a way to access the value, without using a flag which indicates the type of the active value?


Solution

  • No you can't. Unions are unaware of the last type used. You have to either use a plain old integer or add a flag mechanism.