Here is the code
int main()
{
const int i = 2;
const int * pi = &i;
int* j = const_cast<int *> (pi);
*j = 11;
std::cout << *pi << std::endl;
std::cout << i << std::endl;
return 0;
}
result:
11
2 <--- why ?
Here is the code
int main()
{
const int i = 2;
const int * pi = &i;
int* j = const_cast<int *> (pi);
*j = 11;
std::cout << *pi << std::endl;
std::cout << i << std::endl;
return 0;
}
result:
11
2 <--- why ?
As http://en.cppreference.com/w/cpp/language/const_cast puts it:
Even though
const_cast
may remove constness or volatility from any pointer or reference, using the resulting pointer or reference to write to an object that was declaredconst
or to access an object that was declaredvolatile
invokes undefined behavior.
In this case, your compiler has apparently optimized
std::cout << i << std::endl;
to
std::cout << 2 << std::endl;
since i
is const
, and its value cannot change in any valid program. (As it happens, the value of i
did change, because the program is invalid; but your compiler — quite rightly — did not concern itself with that possibility. C++ compilers, and programmers, generally consider it more important to optimize correct code than to mitigate the incorrectness of incorrect code.)