How can cpp show 2 different values at the same memory location after using const_cast on a const int variable

32 views Asked by At

I am trying to change the value of a const int variable (should not be done ideally). This is how I did it.

const int x{5};               //line 1
int* y{const_cast<int*>(&x)}; //line 2

std::cout<<y<<" "<<&x<<endl;  //line 3

*y = 10;                      //line 4
std::cout<<*y<<" "<<x<<endl;  //line 5
std::cout<<y<<" "<<&x<<endl;  //line 6

At line 2, I took away the constness of the constant variable x and made y point to it.

At line 3, the memory address of y and x are same.

But, after I changed the value of y at line 4, line 5 prints *y=10 and x=5, and the weird thing is line 6 still shows the same memory address of y and x.

Can anyone help me understand how things are working internally?

I only want to understand the cause of how the program shows 2 different values at the same memory location.

0

There are 0 answers