如何通过其地址更改const变量的值
How to change value of const variable via its address?
我正在尝试通过其地址更改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
做出各种假设(包括完全从二进制中进行优化!),因为您保证您永远不会更改它。然后您更改它。
今晚没有晚餐!
相关文章:
- 在内存不足之前,我可以声明多少个 const 变量?
- 当设置为 const 变量时使用 nullptr
- 声明与 const 变量和成员函数相同的标识符
- const变量是否可以在具有默认值的参数中赋值(作为可选参数)
- 编译器在传递 const 变量时返回错误:模板参数不是常量表达式
- 在成员函数之间传递const变量为数组的索引
- 为什么静态常量字符 * const 变量在为左值时可绑定到右值引用参数
- C 编译器可以执行用于返回值的命名const变量的RVO
- 如何访问一系列const变量作为const数组
- C 错误C3892:您无法分配const变量
- 是否可以在C++中推迟 const 变量的初始化,例如 Java 的"blank final"功能?
- 为什么将FMTFLAG指定两次 - 作为枚举的一部分,而另一个实例为静态const变量
- 使用非const变量代替所需的const变量(C )
- 使用const变量时,非静态数据成员的使用无效
- 定义,初始化全局const变量是安全的吗?
- const vs non-const变量一旦分配就没有变化
- 为什么设置const变量(将以相同的值存储)会导致不同的结果
- CPP中的私有静态常规成员变量与const变量
- 在避免新分配的同时,const变量的复杂初始化
- 如何通过其地址更改const变量的值