Home > Backend Development > C++ > 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?

Mary-Kate Olsen
Release: 2024-10-28 08:35:02
Original
224 people have browsed it

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:

<code class="cpp">const int e = 2;

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

cout << *w << endl;          // (3)
cout << e << endl;             // (4)</code>
Copy after login

If you run this code, you'll notice an unexpected behavior:

5
2
Copy after login

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.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template