Here is my test code:
#define print(A) cout << #A << " = " << A << endl;
int main()
{
const int e = 2;
int *p = (int *)&e;
*p = 4;
print(e);
print(*p);
print(&e);
print(p);
}
Result:
e = 2;
*p = 4;
&e = 0xbfc6b458;
p = 0xbfc6b458;
Since “p” points to “e” according to their identical address, how can *p and “e” be different??? This can be dangerous, right?
Casting away
constis legal; using the pointer (or reference) thus acquired to (attempt to) modify aconstobject is illegal.Your code results in undefined behaviour; it can do anything and it doesn’t have to make any sense.