关于const的奇怪结果,该怎么处理
关于const的奇怪结果
首先上原代码:
int main(){
const int x=43;
const int *x3 = &x;
int* x4 = (int *)x3;
*x4 = 56; // cast change the original meaning?
const int *x5 = &x;
std::cout<< &x << ": x ="<<x<<std::endl; // output : 43 why??
std::cout<< x5 << ": x5 ="<<*x5<<std::endl; // output : 56
std::cout<< x3 << ": x3="<<*x3<<std::endl; // output : 56
std::cout<< x4 << ": x4="<<*x4<<std::endl; // output : 56
return 0;
}
第一行的输出是43,但地址与x3,x4,x5完全一样, 哪位大侠能解释一下吗?
------解决方案--------------------
这个叫常量折叠,虽然通过x4真的修改了x的值,但任何使用x的地方都用x的初值代替,才会出现这种现象。是一种巧妙的折中,但是*x4=56仍然属于未定义行为,不应使用这样的代码。
------解决方案--------------------
这个是编译器优化的结果,可以google“常量折叠"
首先上原代码:
int main(){
const int x=43;
const int *x3 = &x;
int* x4 = (int *)x3;
*x4 = 56; // cast change the original meaning?
const int *x5 = &x;
std::cout<< &x << ": x ="<<x<<std::endl; // output : 43 why??
std::cout<< x5 << ": x5 ="<<*x5<<std::endl; // output : 56
std::cout<< x3 << ": x3="<<*x3<<std::endl; // output : 56
std::cout<< x4 << ": x4="<<*x4<<std::endl; // output : 56
return 0;
}
第一行的输出是43,但地址与x3,x4,x5完全一样, 哪位大侠能解释一下吗?
------解决方案--------------------
这个叫常量折叠,虽然通过x4真的修改了x的值,但任何使用x的地方都用x的初值代替,才会出现这种现象。是一种巧妙的折中,但是*x4=56仍然属于未定义行为,不应使用这样的代码。
------解决方案--------------------
这个是编译器优化的结果,可以google“常量折叠"
- C/C++ code
int main(){ const volatile int x=43; const volatile int *x3 = &x; int* x4 = (int *)x3; *x4 = 56; // cast change the original meaning? const volatile int *x5 = &x; std::cout<< &x << ": x ="<<x<<std::endl; // output : 43 why?? std::cout<< x5 << ": x5 ="<<*x5<<std::endl; // output : 56 std::cout<< x3 << ": x3="<<*x3<<std::endl; // output : 56 std::cout<< x4 << ": x4="<<*x4<<std::endl; // output : 56 system("pause"); return 0; }
------解决方案--------------------
长长见识,学习!
------解决方案--------------------
http://www.cnblogs.com/chenyuming507950417/
------解决方案--------------------
相当于给你另创建了个变量存放你修改后的值。
------解决方案--------------------
为了避免你通过指针修改常量的值,当你将指针指向常量时编译器给另外分配了一个地址,并将常量的值复制进去,然后让你的指针指向了新的地址。