The reason is that your compiler has inlined the value of i
into the code when compiling this line:
cout << "i: " << i << "\t*ptr: " << *ptr << endl;
Because i
is a const
variable, the compiler has optimised the code by replacing i
in the above line with 10
. If we look at the generated assembly (I'm using VS2010):
002314F2 mov ecx,dword ptr [ptr] // ptr is being pushed here (110)
002314F5 mov edx,dword ptr [ecx]
002314F7 push edx
002314F8 push offset string "\t*ptr: " (23783Ch)
002314FD mov ebx,esp
002314FF push 0Ah // 0Ah is being pushed here (A is hex for 10)
00231501 push offset string "i: " (237830h)
What has happened is that you have modified the constant in memory, but the generated assembly doesn't actually use the memory address - it simply outputs '10' regardless of what's in memory.
As said by Kerrek, this is undefined behavior, so other compilers may do something completely different to this.
In general it is a bad idea to use const_cast
with few exceptions.