Search code examples
cunions

accessing unassigned value of a different type in a union


I have this code:

typedef union MyUnion {
    int ival;
    float fval;
} MyUnion;

MyUnion myUnion;
myUnion.fval = 3.0f;

someFuncCall(myUnion.ival);

What exactly am I doing when I ask for the ival? It is my guess that I am asking for the float to be thought of (encoded as?) an int. I also assume that it has to do with sharing the same space in memory? However, I am definitely uncertain. This is a trick I had to use when sending float data to an FPGA in the Vivado Suite. All data is expected to enter as ints. I'd really appreciate any thorough clarification for what is going on or just pointers to resources. Thanks!


Solution

  • According to the standard IEC9899/2011 §6.5.2.3, note 95 you have that:

    If the member used to read the contents of a union object is not the same as the member last used to store a value in the object, the appropriate part of the object representation of the value is reinterpreted as an object representation in the new type as described in 6.2.6 (a process sometimes called ‘‘type punning’’). This might be a trap representation.

    So indeed what you are trying to do works but it could lead to problems (eg. different sizes for the members or different memory alignment).