"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Does Modifying a `const` Variable Through a Non-Const Pointer Seem to Work, but Doesn\'t Actually Change Its Value?

Why Does Modifying a `const` Variable Through a Non-Const Pointer Seem to Work, but Doesn\'t Actually Change Its Value?

Published on 2024-11-07
Browse:719

Why Does Modifying a `const` Variable Through a Non-Const Pointer Seem to Work, but Doesn\'t Actually Change Its Value?

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:

const int e = 2;

int* w = (int*)&e;        // (1)
*w = 5;                   // (2)

cout 

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:

  • (1) Dereferencing a const pointer (w) allows for modification.
  • (2) The modified value is stored in the memory location pointed to by w, which in this case is the memory location where e is stored.
  • However, the compiler optimizes the code, treating e as a compile-time constant and not evaluating it at runtime.

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3