Modifying a const object engenders undefined behaviour.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
int main()
{
constint i = 8 ;
constint* p = &i ;
std::cout << "int at address " << &i << " has value " << i << '\n'
<< "int at address " << p << " has value " << *p << "\n\n" ;
const_cast<int&>(i) = 56 ; // **** UB
std::cout << "int at address " << &i << " has value " << i << '\n'
<< "int at address " << p << " has value " << *p << "\n\n" ;
*const_cast<int*>(p) = 99 ; // **** UB
std::cout << "int at address " << &i << " has value " << i << '\n'
<< "int at address " << p << " has value " << *p << "\n\n" ;
}
clang++ -std=c++11 -stdlib=libc++ -O3 -Wall -Wextra -pedantic-errors main.cpp -lsupc++ && ./a.out
int at address 0x7fff178ac1f8 has value 8
int at address 0x7fff178ac1f8 has value 8
int at address 0x7fff178ac1f8 has value 8
int at address 0x7fff178ac1f8 has value 56
int at address 0x7fff178ac1f8 has value 8
int at address 0x7fff178ac1f8 has value 99
This is Undefined Behavior for you. When you trigger it, anything can happen, including formatting your hard drive and making demons to fly out of your nose. It is allowed for program to behave that way.
What probably happens is that all entry of i are replaced by 8 in compile time. Compiler can do that, as you declared variable to be constant, and therefore promised that it won't be ever changed.
If this variable would have static storage duration instead of automatic, it would be likely placed in read only memory and any attempt to change it would lead to crash.
So, in any situation, never change value of constant variable.