I am trying to change the value of a variable which is defined as int const as below.
const int w = 10;
int* wp = const_cast <int*> (&w);
*wp = 20;
The value of w didn't change and was 10 even after the assignment, though it shows as if both w and wp are pointing to the same memory location. But I am able to the change the value of w, if defined as below while declaring
int i = 10;
const int w = i;
If I change the declaration of i to make it const like in
const int i = 10;
The value of w doesn't change.
In the first case, how come the value of w didn't change, even though w and wp point to the same memory location [ that was my impression I get when I print their addresses ]
What difference it's to the compiler that it treats both the cases differently?
Is there a way to make sure that w doesn't lose constness, irrespective of the way it is defined?