0

Depending on optimization level the output differ as follows:

With unexpected output:

$ gcc -Wall -O3  otest.c -o otest                   
$ otest                                             
*x: 0 
y: 2048.899902 
y: 0.000000 

With expected output:

$ gcc -Wall -O2  otest.c -o otest 
$ otest                           
*x: 45000e66 
y: 0.000000 
y: 2048.899902

source code :

#include <stdio.h>
int main(void)
{
   float y = 2048.9;
   void *p = &y;
   unsigned int *x = p;
   printf(" *x: %x \n",*x);
   *x = 0; 
   printf(" y: %f \n",y);
   *x = 0x45000e66;
   printf(" y: %f \n",y);  
   return 0;
 }

gcc version is 4.2.1.

Am I missing any important directive ?

1 Answers1

4

Yes. Your code is violating the strict aliasing rule (when you have a float, but you access it through a pointer to unsigned int, which is an incompatible type), invoking undefined behavior, so the compiler is allowed to do anything it pleases with your code, including entirely eliminating parts of it.

  • It might be worth pointing out that compilers these days do try to do the right thing -- they'll generate their code presuming circumstances that would lead to undefined behavior don't exist, which can open up quite a lot of optimization opportunities... – jthill Apr 30 '14 at 15:01