I'm trying to write a program that changes the value of a const
variable. I know this shouldn't be done this in the first place and I'm doing this just to know how this happen.
我已经读过其他有关此问题,但我不是想知道如何去做,而是为什么它在我的程序中没有发生。这是我写的代码:
int main()
{
const int a = 5;
int *pointer_a = const_cast<int*>(&a);
*pointer_a = 6;
// Address of a
std::cout << &a << std::endl;
// Prints 5 while memory says it is 6
std::cout << a << std::endl;
// Address that pointer points too
std::cout << pointer_a << std::endl;
// Prints 6
std::cout << *pointer_a << std::endl;
}
What I noticed while debugging this program is that in fact the value at the memory address of a
gets updated. It does change the value of a
from 5
to 6
.
The IDE (Visual Studio) also shows the value of a
to be 6
but when printing it to the console, it prints 5
. Why does this happen when the current value on the memory is 6
?.
尝试关闭编译器优化标志(项目属性,C / C ++,优化)
It is undefined behaviour to modify a value which is initially declared as
const
.https://en.cppreference.com/w/cpp/language/const_cast: