为什么同一个内存位置同时保持不同的值?

Inq*_*ive 1 c++

在以下程序中,相同的内存位置如何保持不同的值?我正在使用g ++编译器.

码:

#include<iostream>
using namespace std;

int main()
{
   const int i=100;
   int *j = const_cast<int*>(&i);
   *j=1;

   cout<<"The value of i is:"<<i<<endl;
   cout<<"The value j holds:"<<*j<<endl;
   cout<<"The address of i is:"<<&i<<endl;
   cout<<"The address of j is:"< <j<<endl;

}
Run Code Online (Sandbox Code Playgroud)

输出:

The value of i is:100
The value j holds:1
The address of i is:0xbffbe79c
The address of j is:0xbffbe79c
Run Code Online (Sandbox Code Playgroud)

Jam*_*nze 6

你有未定义的行为,所以任何事情都可能发生.在这种情况下,编译器知道i不能更改值,并且可能只是直接使用该值.