While I assign a const int to simple int pointer (via type casting), and then changed value of pointer. Now pointer giving me updated value but const int giving the same! Can anybody please explain what is going on here?
Here is sample code:
int main() {
const int val = 5;
int *p = (int*)&val;
cout<<"val: "<<val<<endl;
cout<<"*p: "<<*p<<endl;
*p = 64;
cout<<"*p: "<<*p<<endl;
cout<<"val: "<<val<<endl;
cout<<"p: "<<p<<endl;
cout<<"&val: "<<&val<<endl;
int *p1 = (int*)&val;
cout<<"*p1: "<<*p1<<endl;
const int *p2 = &val;
cout<<"*p2: "<<*p2<<endl;
return 0;
}
Here is the output:
val: 5
*p: 5
*p: 64
val: 5
p: 0x7ffcb2de795c
&val: 0x7ffcb2de795c
*p1: 64
*p2: 64
Here main point is, address stored in "p" is same as address of "val". Also any later pointer we are assigning (even const int *) reflecting changed value not original one.