Possible Duplicate:
Modifying a const through a non-const pointer
lets’ see the code below first.very short code:
int main()
{
const int n=9;
int *p=(int*)&n;
*p=5;
cout<<*p<<endl; //result is 5
cout<<n<<endl; // 9
int a=n+1;
cout<<a<<endl; // 10
}
To my surprise,the compiler doesn’t complain at all.And the result is as what i showed as comment.
But,if that makes sense more or less.What’s more astonishing is that,
when you debug it, you can see that the value of n has actually changed to 5!
But then ,when you use “n”,it seemed that the “n” is still treated as the original value 9!
So i guess the compiler has stored the original value of “n” in somewhere else, right?
Then where is the original value of “n”,which is 9, stored now?
Thank you for all your help!
This probably due to optimizations. Since you declare
const int n=9, you’re basically making a promise that you won’t modifyn. So the compiler is free to optimizecout << n << endl;to a simplecout << 9 << endl;. I don’t think the old value is stored anywhere else.Nevertheless, this is undefined behavior.
I can confirm that the cause of this behavior is optimization, even on a debug build:
ndoesn’t even come into discussion.If
nwasn’tconst, the optimization would be illegal:Here, the value of
nis pushed on the argument stack because it’s notconst.