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

How to change value of const variable via its address?

本文关键字:const 变量 何通过 地址      更新时间:2023-10-16

我正在尝试通过其地址更改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("%pn", &x);
    *b = 10;
    cout<< &x << " " << x << " " << b << " " << *b << " " << *(reinterpret_cast<uint64_t*>(0x28ff10)) <<endl;
    return 0;
}

用mingw 4.8.1编译:

g -g main.cpp&amp;&amp;./a.exe

这是输出:

18446744073709551615
0x28ff10 0x28ff10 18446744073709551615
0028FF10
0x28ff10 18446744073709551615 0x28ff10 10 10

有人可以解释吗?

编辑:弄清楚了!尽管我用-O0编译了它,但编译仍然优化了我的变量。看了生成的ASM,我看到printf和cout直接放置了值,而不是变量符号。

所以,要使我的代码做正确的行为,我必须用volatile static

声明它。

我正在尝试通过其地址更改const变量的值。

到目前为止,您已经出错了。

const是"常数"的简短。

您不能突变常数。

有时您可以使它看起来像您一样,但是这样做的行为不确定。您告诉编译器,它可以对x做出各种假设(包括完全从二进制中进行优化!),因为您保证您永远不会更改它。然后您更改它。

编译器先生说,

今晚没有晚餐!