I understand that const_cast
works with pointers and references.
I\'m assuming that the input to const_cast
should be a pointe
Modifying the constant via the const_cast
is undefined behaviour.
The compiler sees that you are trying to print a constant variable, knows it can never change so compiles:
cout << "i: " << i << endl;
to:
cout << "i: " << 123 << endl;
see: https://godbolt.org/z/bYb0mx. With optimisations enabled it optimises your code to just printing 123: https://godbolt.org/z/4Ttlmj.
Ultimately compilers make assumptions in order to create faster/smaller code, if you enter the realms of undefined behaviour some of those assumptions may be incorrect and produce surprising results.