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.
I've already read other questions about this but I'm not trying to know how to do it but why it isn't happening in my program. This is the code I wrote:
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
?.
It is undefined behaviour to modify a value which is initially declared as const
.
https://en.cppreference.com/w/cpp/language/const_cast:
const_cast
makes it possible to form a reference or pointer to non-const type that is actually referring to a const object. Modifying a const object through a non-const access path results in undefined behavior.