#include <iostream>
using namespace std;
int main() {
const int a = 2;
const int *p = &a;
int *p2 = const_cast<int*>(p);
*p2=5;
char *p3 = (char *)&a;
cout << "p2 is" << *p2 << endl;
cout << "p2 address " << p2 << endl;
cout << "a is " << a << endl;
cout << "a address " << &a << endl;
return 0;
}
Hi all!
According to the output, *p2 and a has different values, *p2 is 5 and a is 2.
However, p2 and &a are the same. I’m confused…
Could you please help me understand where this is the case?
Thank you very much!
Undefined behavior means that anything can happen. Including this.
5.2.11 Const cast [expr.const.cast]
The underlying reason might be that the compiler, seeing how
aisconst, optimizescout << "a is " << a << endl;to a simplecout << "a is " << 2 << endl;.For example, even in a debug build, I get:
I highlighted the essential part –
2is pushed directly on the argument stack ofoperator<<, instead of the value ofabeing read.