title: Type punning and Unions in C
body: <p>I'm currently working on a project to build a small compiler just for the heck of it.</p>
  
  <p>I've decided to take the approach of building an extremely simple virtual machine to target so I don't have to worry about learning the ins and outs of elf, intel assembly, etc.</p>
  
  <p>My question is about type punning in C using unions. I've decided to only support 32 bit integers and 32 bit float values in the vm's memory. To facilitate this, the "main memory" of the vm is set up like this:</p>
  
  <pre><code>typedef union
  {    
      int i;
      float f;
  }word;
  
  
  memory = (word *)malloc(mem_size * sizeof(word));
  </code></pre>
  
  <p>So I can then just treat the memory section as either an int or a float depending on the instruction.</p>
  
  <p>Is this technically type punning? It certainly would be if I were to use ints as the words of memory and then use a float* to treat them like floats. My current approach, while syntactically different, I don't think is semantically different. In the end I'm still treating 32 bits in memory as either an int or a float.</p>
  
  <p>The only information I could come up with online suggests that this is implementation dependent. Is there a more portable way to acheive this without wasting a bunch of space?</p>
  
  <p>I could do the following, but then I would be taking up more than 2 times as much memory and "reinventing the wheel" with respect to unions.</p>
  
  <pre><code>typedef struct
  {
      int i;
      float f;
      char is_int;
  }
  </code></pre>
  
  <p><strong>Edit</strong></p>
  
  <p>I perhaps didn't make my exact question clear. I am aware that I can use either a float or an int from a union without undefined behavior. What I'm after is specifically a way to have a 32 bit memory location that I can safely use as an int or float without knowing what the last value set was. I want to account for the situation where the other type is used.</p>