The other day, a C++ trainer said to me that “const” does have meaning only in compile time (statically) and thus doesn’t have an influence in runtime… but when I test this example :
const int x = 5; int * px = const_cast(&x); *px = 10; std::cout << "x = " << x <<std::endl; // x = 5 ???
x is not modified with 10 ! whereas, this example works as expected if we use pointers:
const int * x = new int(5); int * px = const_cast(x); *px = 10; std::cout << "x = " << *x <<std::endl; // x = 10
So, this C++ trainer is wrong ?
It’s undefined behaviour to modify a
. This allows the compiler to optimise your code assuming it never happens. In your first code example, the compiler probably inserted a literal
in the code during the call to
Your second example is completely well defined, because
is really pointing at an
. In this case, casting away the
ness is fine.