C++指针混乱

Sid*_*qui 0 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;
}
Run Code Online (Sandbox Code Playgroud)

CB *_*ley 11

*ptr = 8;
Run Code Online (Sandbox Code Playgroud)

此行导致未定义的行为,因为您正在修改const限定对象的值.一旦你有未定义的行为,任何事情都可能发生,并且无法推断程序的行为.


Jes*_*per 6

由于x是a const int,编译器很可能在您使用的地方x直接替换您初始化的值(如果可能).所以源代码中的行:

cout<<"x: "<<x<<endl;
Run Code Online (Sandbox Code Playgroud)

将在编译时替换为:

cout<<"x: "<<10<<endl;
Run Code Online (Sandbox Code Playgroud)

这就是为什么你仍然看到10印刷.

但正如Charles解释的那样,行为是未定义的,所以任何事情都可能发生在这样的代码上.