简体   繁体   English

gcc -O3,数据指针似乎丢失了

[英]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. gcc版本是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. 您的代码违反了严格的别名规则(当您有float ,但是通过指向unsigned int的指针访问它,这是一个不兼容的类型),调用了未定义的行为,因此允许编译器对您的代码执行任何其喜欢的操作,包括完全消除其中的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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