我很好奇为什么我的研究结果很奇怪
#include <iostream>
int test()
{
return 0;
}
int main()
{
/*include either the next line or the one after*/
const int a = test(); //the result is 1:1
const int a = 0; //the result is 0:1
int* ra = (int*)((void*)&a);
*ra = 1;
std::cout << a << ":" << *ra << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为什么常量 var initialize while runtime 可以完全改变,而 initialize while compile 只会改变指针的 var?
该功能在这里并不那么相关。原则上,您可以通过此代码获得相同的输出(0:1):
int main() {
const int a = 0;
int* ra = (int*)((void*)&a);
*ra = 1;
std::cout << a << ":" << *ra;
}
Run Code Online (Sandbox Code Playgroud)
a是const int不是int。您可以执行各种无意义的 c 转换,但修改const对象会调用未定义的行为。
顺便说一句,在上面的示例中,即使std::cout << a << ":" << a;编译器也被允许发出打印1:0(或42:3.1415927) 的代码。当你的代码有未定义的行为时,任何事情都可能发生。
PS:如果您想研究编译器的内部结构以及它对无效 C++ 代码的作用,则该函数和不同的结果是相关的。为此,您最好查看编译器的输出以及它在两种情况下的差异(https://godbolt.org/)。