title: Dereferencing type-punned pointer will break strict-aliasing rules
body: <p>I used the following piece of code to read data from files as part of a larger program.</p>
  
  <pre><code>double data_read(FILE *stream,int code) {
          char data[8];
          switch(code) {
          case 0x08:
              return (unsigned char)fgetc(stream);
          case 0x09:
              return (signed char)fgetc(stream);
          case 0x0b:
              data[1] = fgetc(stream);
              data[0] = fgetc(stream);
              return *(short*)data;
          case 0x0c:
              for(int i=3;i&gt;=0;i--)
                  data[i] = fgetc(stream);
              return *(int*)data;
          case 0x0d:
              for(int i=3;i&gt;=0;i--)
                  data[i] = fgetc(stream);
              return *(float*)data;
          case 0x0e:
              for(int i=7;i&gt;=0;i--)
                  data[i] = fgetc(stream);
              return *(double*)data;
          }
          die("data read failed");
          return 1;
      }
  </code></pre>
  
  <p>Now I am told to use <code>-O2</code> and I get following gcc warning:
  <code>warning: dereferencing type-punned pointer will break strict-aliasing rules</code></p>
  
  <p>Googleing I found two orthogonal answers:</p>
  
  <ul>
  <li><a href="http://bytes.com/topic/c/answers/800137-dereferencing-type-punned-pointer-will-break-strict-aliasing-rules" rel="noreferrer">Concluding: there's no need to worry; gcc tries to be more law obedient than 
  the actual law.</a> </li>
  </ul>
  
  <p>vs</p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule/98702#98702">So basically if you have an int* and a float* they are not allowed to point to the same memory location. If your code does not respect this, then the compiler's optimizer will most likely break your code.</a></li>
  </ul>
  
  <p>In the end I don't want to ignore the warnings. What would you recommend?</p>
  
  <p><strong>[update]</strong> I substituted the toy example with the real function.</p>