变更常数 [英] Change constant value
问题描述
不是重复项.请阅读完整问题.
Not a Duplicate. Please read Full question.
#include<iostream>
using namespace std;
int main()
{
const int a = 5;
const int *ptr1 = &a;
int *ptr = (int *)ptr1;
*ptr = 10;
cout<<ptr<<" = "<<*ptr<<endl;
cout<<ptr1<<" = "<<*ptr1<<endl;
cout<<&a<<" = "<<a;
return 0;
}
输出:
0x7ffe13455fb4 = 10
0x7ffe13455fb4 = 10
0x7ffe13455fb4 = 5
这怎么可能?
推荐答案
这肯定是未定义的行为,但是我坚决支持理解未定义行为的症状以利于发现一个行为.观察到的结果可以用以下方式解释:
It is certainly undefined behavior, but I am strong proponent of understanding symptoms of undefined behavior for the benefit of spotting one. The results observed can be explained in following manner:
const int a = 5
定义的整数常量.现在,编译器假定在整个函数期间不会修改该值,因此在看到
defined integer constant. Compiler now assumes that value will never be modified for the duration of the whole function, so when it sees
cout<<&a<<" = "<<a;
它不会生成代码来重新加载a
的当前值,而是仅使用初始化时使用的数字-比从内存中加载要快得多.
it doesn't generate the code to reload the current value of a
, instead it just uses the number it was initialized with - it is much faster, than loading from memory.
这是一种非常常见的优化技术-当某个条件只有在程序表现出未定义的行为时才会发生,优化器会认为该条件永远不会发生.
This is a very common optimization technique - when a certain condition can only happen when the program exhibits undefined behavior, optimizers assume that condition never happens.
这篇关于变更常数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!