Home >Backend Development >C++ >Why does modifying a `const` value through a non-const pointer lead to undefined behavior but still print different values for the pointer and the original variable?
Modifying a const through a Non-const Pointer
Consider the following code:
<code class="cpp">const int e = 2; int* w = (int*) &e; // (1) cast to remove const-ness *w = 5; // (2) cout << *w << endl; // (3) outputs 5 cout << e << endl; // (4) outputs 2 cout << "w = " << w << endl; // (5) w points to the address of e cout << "&e = " << &e << endl;</code>
In (1), w points to the address of e. In (2), that value is changed to 5. However, when the values of *w and e are displayed, their values are different. But if you print the pointer w and the address of e, they have the same value.
How come e still contains 2, even if it was changed to 5? Were they stored in a separate location? Or a temporary? But how come the value pointed by w is still the address of e?
Answer
Once you modify a const value, you enter undefined behavior territory. However, to speculate:
The above is the detailed content of Why does modifying a `const` value through a non-const pointer lead to undefined behavior but still print different values for the pointer and the original variable?. For more information, please follow other related articles on the PHP Chinese website!