Someone showed me the following code snippet and asked what it should output
#include <iostream>
using namespace std;
int main() {
const int value = 10;
int* p = (int*)&value;
*p = 20;
cout << value << " " << *p << endl
<< &value << " " << p << endl;
return 0;
}
As you can see, there's a constant value
which is 10, and there's a pointer p
which points to the address of value, then the address pointed gets a different value.
I expected the program to print 20 20
but it actually prints 10 20
.
It also shows that the two valuables have the same address. Can someone explain what's going on behind the scenes here?