Modifying a const Through a Non-Const Pointer
In C , a const variable cannot be modified once initialized. However, in certain scenarios, it may appear that a const variable has been altered. Consider the following code:
<code class="cpp">const int e = 2; int* w = (int*)&e; // (1) *w = 5; // (2) cout << *w << endl; // (3) cout << e << endl; // (4)</code>
If you run this code, you'll notice an unexpected behavior:
5 2
Even though *w was changed to 5 in (2), e still holds its original value of 2. This seemingly paradoxical behavior stems from the following factors:
As a result, when *w is evaluated at runtime, it returns the modified value (5). However, when e is evaluated at compile time, its original value (2) is used.
This behavior is known as undefined behavior in C . Modifying a const variable directly or indirectly leads to unpredictable consequences, and caution should be exercised in such situations.
The above is the detailed content of Why Does Modifying a `const` Variable Through a Non-Const Pointer Seem to Work, but Doesn\'t Actually Change Its Value?. For more information, please follow other related articles on the PHP Chinese website!