I was asked how to change the value of a constant variable.
My obvious answer was "pointers!". but I tried the following code snippet and I am puzzled ...
int main() { const int x = 5; int *ptr = (int *)(&x); // "Cast away" the const-ness.. cout << "Value at " << ptr << ":"<< (*ptr) <<endl; *ptr = 6; cout << "Now the value of "<< ptr << " is: " << (*ptr) <<endl; cout << "But the value of x is still " << x <<endl; return 0; }
And the result was:
Value at <some address> :5 Now the value of <same address> is: 6 But the value of x is still 5
Now I'm not sure exactly what is returned from '& x', but this is definitely not the actual address of x, since the value in x has not been changed!
But on the other hand, ptr did contains the value x at the beginning! So what is it?
EDIT compiled with VS2010
Avraham shukron
source share