简体   繁体   中英

gcc -O3 , data pointer seems to get lost

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM