通过非常量指针修改常量

我对以下代码中发生的事情感到有些困惑:



const int e = 2;


int* w = ( int* ) &e;          // (1) cast to remove const-ness

*w = 5;                        // (2)


cout << *w << endl;            // (3) outputs 5

cout << e << endl;             // (4) outputs 2


cout << "w = " << w << endl;   // (5) w points to the address of e

cout << "&e = " << &e << endl;

在(1)中,w指向e的地址。在(2)中,该值更改为5。但是,当显示* w和e的值时,它们的值不同。但是,如果您打印w指针和&e的值,则它们具有相同的值/地址。


即使更改为5,e为何仍包含2?它们是否存储在单独的位置?还是临时的?但是,为什么w指向的值仍然是e的地址?


婷婷同学_
浏览 554回答 3
3回答

郎朗坤

就像我在评论中说的那样,一旦您修改了const值,您就处于未定义的行为状态,因此谈论正在发生的事情并没有多大意义。可是什么cout << *w << endl;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // (3) outputs 5cout << e << endl;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// (4) outputs 2猜测*w是在运行时进行评估,但e被视为编译时间常数
打开App,查看更多内容
随时随地看视频慕课网APP