#include<iostream>
//const关键字保护变量不可被改变
/*const_demo.cpp
问题描述:
加断点调试时可以看到a的值在*p赋值后变成了8,但由于const的
作用最后输出的还是7。问题是:为什么在断点调试时可以看到a变
成了8?
*/
using namespace std;
int main(void)
{
const int a = 7;
int *p = (int*)&a;
*p = 8;
cout<<a;
return 0;
}
我用vscode测试*p 是 7啊
From https://en.cppreference.com/w/cpp/language/cv
const object - an object whose type is const-qualified, or a non-mutable subobject of a const object. Such object cannot be modified: attempt to do so directly is a compile-time error, and attempt to do so indirectly (e.g., by modifying the const object through a reference or pointer to non-const type) results in undefined behavior.
因为const变量a被优化到寄存器上了,而通过p访问的a是内存中的a。