There is such code:
#include <iostream>
int main(){
const int a = 2;
int* ptr = (int*)&a;
*ptr = 3;
std::cout << &a << " " << ptr << " " << a << " " << *ptr << std::endl;
return 0;
}
Result:
0xbf88d51c 0xbf88d51c 2 3
Why these two values differ? What does it here happen?
This is dangerous (this itself doesn’t invoke UB, though). But this,
This invokes undefined behavior (UB), because you’re attempting to modify the
constobject pointing to byptr. UB means anything could happen. Note thatais truly a const object.§7.1.5.1/4 (C++03) says,