const_cast
causes undefined behaviour if you cast away const
then write to the value. Not doing anything is valid behaviour, as you have seen here.
In your particular example, what has likely happened is that the compiler sees that k
is declared with the const
storage class, knows that it can't (legally) change, and replaces
cout<<"k after="<<k<<endl;
with
cout<<"k after="<<1<<endl;
If you turn off optimisations you may (or may not) get a different result.
The very reason that casting away const
invokes undefined behaviour is so that the compiler is free to do optimisations like this. If const
variables could be freely cast to non-const
variables and written to, then const
would be absolutely meaningless to the compiler.