Possible Duplicate:
Modifying a const through a non-const pointer
I have the following code:
const int x = 5;
int *p = (int*)&x;
*p = 2; // Line 1
cout << x << " - " << *p << endl;
cout << &x << " - " << p << endl;
And got the results:
5 - 2
0012FF28 - 0012FF28
I know the code is weird and should never do it. But I wondered why the same address but got different result? And where the Line 1 store the number 2?
Because changing the value of an inherently
constvariable in anyway is Undefined Behavior[Ref #1].Once you did:
All bets are off, and your code is no longer a valid C++ code, You cannot expect any particular behavior once that line was written. To speculate why an Undefined Behavior gives any particular behavior is pointless because it is allowed to show any behavior[Ref #2] that is the meaning of Undefined Behavior.
[Ref #1]
C++03 Standard 7.1.5.1 The cv-qualifiers:
Para 4:
[Ref #2]
C++03 Standard 1.3.24: