简体   繁体   中英

Assigning and getting union values, type punning

I have a union, ok.
This union is inside a struct, and that union is unnamed (something) like that.

typedef enum TYPES {INT, FLOAT, CHAR, POINTER TO FUNCTION /* Please pay attention on this */};

typedef struct {
    TYPES type;
    union {
        int integer;
        float real;
        char letter;
        char *string;
        /* here we have a pointer to function syntax but I don't remember how to write it right now*/
    }
} MY_STRUCT;

I will initialze my struct like this way.

MY_STRUCT test = {INT, 22};

Ok I know that this work because, by definition, when I use this kind of initialization the most first field of the union will be used.
So the question is:
what happens if I write the initialization like this?

MY_STRUCT test = {INT, 22.2};

After when I try to retrieve the float value I will get the right value?

float var = (float)test.real;

Will this show the right thing?
Will this work for every type? Even the pointer to function one?

I'm asking this because by definition that initialization puts the value in the very first field of my union, so, is there a problem if float is bigger than int? I don't know this, so, I'm aware about the pointer to function that sometimes it could be bigger than an int, so I need to write my union with the pointer to function as the very first member?

I read that GCC supports type punning and even the linux kernel use type punning. So I'm only afraid if I can use this kind of initialization on that struct, and after that, get the right values.

Elements of union shares memory space, whole union uses space what is needed for "bigest" element. When you initalize with 22.2 . That represents with 01000001101100011001100110011010 using fpoint IEEE 754. It depends of precision. and your

float var=(float) test.real

will work only if you do not change any element of union between initalization and this line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM