Why warnings prevent us from writing optimized programs? : <p>Check out this code:</p>

<pre><code>#include &lt;stdio.h&gt;

unsigned short GetShort_With_Warning( unsigned long long val ) {
    return *(unsigned short*)&amp;val;
    // mov  ax,word ptr [val] // That's it. Elegance
}

unsigned short GetShort_Without_Warning( unsigned long long val ) {
    unsigned short* shv = (unsigned short*)&amp;val;
    // lea  eax,[val]
    // mov  dword ptr [shv],eax
    return *shv;
    // mov  eax,dword ptr [shv]  
    // mov  ax,word ptr [eax]  
}

int main( void ) {
    printf( "%04x\n", GetShort_With_Warning   ( 0x101234ULL ) );
    printf( "%04x\n", GetShort_Without_Warning( 0x101234ULL ) );
    return 0;
}
</code></pre>

<p>This is just an example...<br>
There are two functions that do the same, but one gives a warning and the other does not. The assembler code is shown with a comment. Can it be made that the 'elegant' decision does not give a warning?</p>

<p>It's compiled with g++:</p>

<pre><code>g++ -Wall -O3 -s -I. -c -o main.o main.cc
</code></pre>

<p>The following warning appears:</p>

<pre><code>main.cc:4:28: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
  return *(unsigned short*)&amp;val;
                            ^~~
</code></pre>

<p>I know what the warning wants to say me.<br>
I know that with today's CPU power this case is not a problem.</p>

<p>Anyway...
My question is why the warnings don't allow me to optimize my code?</p>
