Have a look at this code, it shows some astonishing results.
1: #include <iostream.h>
2: using namespace std;
3:
4: int main()
5: {
6: const int x = 10;
7: int * ptr;
8: ptr = (int *)( &x ); //make the pointer to constant int*
9:
10: *ptr = 8; //change the value of the constant using the pointer.
11:
12: //here is the real surprising part
13: cout<<"x: "<<x<<endl; //prints 10, means value is not changed
14: cout<<"*ptr: "<<*ptr<<endl; //prints 8, means value is changed
15: cout<<"ptr: "<<(int)ptr<<endl; //prints some address lets say 0xfadc02
16: cout<<"&x: "<<(int)&x<<endl; //prints the same address, i.e. 0xfadc02
17: //This means that x resides at the same location ptr points to yet
18: //two different values are printed, I cant understand this.
19:
20: return 0;
21: }
If anyone knows the reason, please post it here.
When the compiler analyzes your code, it does not see your intentions. It merely sees a (too weak) guarantee that x is not going to change, so it chooses the liberty to inline 10 when printing. On line 13 it simply does not refer to the variable anymore, it just prints immediate value. (Check the disassembly to see if I’m right).
However, because of your breakage of the promise to keep x const (assignment on line 10), the behavior of the program is undefined. It could print 10, 8, 666 or whatever. It could even crash if the system used some funny memory model for consts.
-rtfb