如何通过地址更改const变量的值?

Lon*_*gLT -2 c++ pointers const

我试图通过其地址更改const变量的值.

遵循以下代码:

#include <iostream>
#include <string>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
#include <stdio.h>

using namespace std;

int main(void)
{
    uint64_t const x = -1;
    uint64_t *b = reinterpret_cast<uint64_t*>(0x28ff10);
    cout<< x << endl;
    cout<< &x << " " << b << " " << *b << endl;
    printf("%p\n", &x);
    *b = 10;
    cout<< &x << " " << x << " " << b << " " << *b << " " << *(reinterpret_cast<uint64_t*>(0x28ff10)) <<endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

使用MinGW编译4.8.1:

g ++ -g main.cpp && ./a.exe

这是输出:

18446744073709551615
0x28ff10 0x28ff10 18446744073709551615
0028FF10
0x28ff10 18446744073709551615 0x28ff10 10 10
Run Code Online (Sandbox Code Playgroud)

谁能解释一下呢?

编辑:想通了!编译仍然优化我的变量,虽然我用它编译-O0.看着生成的ASM,我看到printf和cout直接放入值而不是变量符号.

因此,为了使我的代码做正确的行为,我必须用它来声明它 volatile static

Lig*_*ica 5

我试图通过其地址更改const变量的值.

到目前为止你已经出了问题.

const 是"常数"的缩写.

你不能改变常数.

有时你可以让它看起来像你做的那样,但这样做有未定义的行为.你告诉你的编译器它可以做出各种各样的假设x(包括完全从你的二进制文件中优化它!)因为你保证你永远不会改变它.然后你改变它.

Compiler先生说,今晚没有晚餐给你!

  • @LongLT:不,那是胡说八道.特别是在实践中,你正在贬低这个假设:"如果存在地址".编译过程比你给它的信誉要复杂得多.无论如何,正如我在答案中所说,"const"是"常数"的缩写.你无法改变它._这就是它的含义_.你为什么要这么多地改变一个常数?改为使用变量.这就是变量的用途. (2认同)