[英]C++ Pointer Confusion
Please Explain the following code请解释以下代码
#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;
This line causes undefined behavior because you are modifying the value of a const
qualified object.此行会导致未定义的行为,因为您正在修改
const
限定 object 的值。 Once you have undefined behavior anything can happen and it is not possible to reason about the behaviour of the program.一旦你有未定义的行为,任何事情都可能发生,并且无法推断程序的行为。
Since x
is a const int
, the compiler will most likely, in the places where you use x
, directly substitute the value that you've initialized with (where possible).由于
x
是一个const int
,编译器很可能会在您使用x
的地方直接替换您已初始化的值(在可能的情况下)。 So the line in your source code:所以你的源代码中的行:
cout<<"x: "<<x<<endl;
will be replaced by this at compile time:将在编译时替换为:
cout<<"x: "<<10<<endl;
That's why you still see 10 printed.这就是为什么您仍然看到 10 打印出来的原因。
But as Charles explained, the behaviour is undefined, so anything could happen with code like this.但正如查尔斯解释的那样,行为是未定义的,所以像这样的代码可能会发生任何事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.