C ++指针混乱

| 请说明以下代码
#include <iostream>

using namespace std;

int main()
{
    const int x = 10;
    int * ptr;
    ptr = (int *)( &x );    //make the pointer to constant int*
    *ptr = 8;               //change the value of the constant using the pointer.
    //here is the real surprising part
    cout<<\"x: \"<<x<<endl;          //prints 10, means value is not changed
    cout<<\"*ptr: \"<<*ptr<<endl;    //prints 8, means value is changed
    cout<<\"ptr: \"<<(int)ptr<<endl; //prints some address lets say 0xfadc02
    cout<<\"&x: \"<<(int)&x<<endl;   //prints the same address, i.e. 0xfadc02
    //This means that x resides at the same location ptr points to yet 
    //two different values are printed, I cant understand this.

    return 0;
}
    
已邀请:
*ptr = 8;
这行导致未定义的行为,因为您正在修改
const
合格对象的值。一旦您具有未定义的行为,任何事情都可能发生,并且不可能推理程序的行为。     
由于
x
const int
,因此编译器很可能会在您使用
x
的地方直接替换您初始化时使用的值(如果可能)。因此,您的源代码行如下:
cout<<\"x: \"<<x<<endl;
将在编译时替换为:
cout<<\"x: \"<<10<<endl;
这就是为什么您仍然看到10张纸的原因。 但是正如Charles解释的那样,该行为是不确定的,因此此类代码可能会发生任何事情。     

要回复问题请先登录注册