I was trying to modify a const int using pointer. To my surprise, I was able to modify it but was surprised to see that the values when printed out from the const int and through pointer shows different values (even though the memory addresses are the same). Does anybody has any explanation for this behavior ? Below I am posting the code as well as output.
I would greatly appreciate if somebody who is more knowledgeable in C/C++ can help me understand.
Code:
Output:Code:void modify_const(void) { const int x = 1; const int *y; int *z; y = &x; z = const_cast<int *>(y); cout << "Value in y: " << y << endl; cout << "Value in z: " << z <<endl; cout << "Address of x: " << &x << endl; cout << "I was able to do address manipulation to remove constness" << endl; cout << "Value of z is: " << *z << endl; //cout << "Value of x is incremented to: " << ++x << endl; (*z)++; cout << "Value of z is: " << *z << endl; cout << "Value of x is: " << x << endl; cout << "Value in z: " << z <<endl; cout << "Address of x: " << &x << endl; }
Value in y: 0x27ff14
Value in z: 0x27ff14
Address of x: 0x27ff14
I was able to do address manipulation to remove constness
Value of z is: 1
Value of z is: 2
Value of x is: 1
Value in z: 0x27ff14
Address of x: 0x27ff14