Home  >  Article  >  Backend Development  >  Why Does Modifying a Constant through a Non-const Pointer Produce Undefined Behavior?

Why Does Modifying a Constant through a Non-const Pointer Produce Undefined Behavior?

Linda Hamilton
Linda HamiltonOriginal
2024-10-29 05:31:02895browse

Why Does Modifying a Constant through a Non-const Pointer Produce Undefined Behavior?

Modifying a Constant through a Non-const Pointer: Delving into Undefined Behavior

In the provided code snippet, you express confusion over the behavior of modifying a constant integer (e) through a non-const pointer (w):

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

int* w = (int*) &e;  // Casting to remove const-ness
*w = 5;            // Modifying the value pointed to by w</code>

After making this modification, you observe that:

  • Displaying the value pointed to by w (cout << w << endl;) outputs 5, as expected.
  • However, displaying the value of e (*cout << e << endl;) surprisingly outputs 2, its original value.

You further notice that the address pointed to by w is the same as the address of e (cout << "w = " << w << endl;cout << "&e = " << &e << endl;). This leads you to question how e remains unchanged despite the modification made through w.

This behavior stems from the undefined behavior that arises when modifying a constant through a non-const pointer. Once you make such a modification, the code enters undefined behavior territory, where it becomes unpredictable and depends on specific implementation details.

In this case, it appears that the modification through w affects a temporary copy of e at runtime, while the original e remains unchanged. The reason for this is that e is treated as a compile-time constant, and its value is hardcoded into the binary code. Therefore, any runtime modifications to w will not affect the original e.

This behavior is specific to the implementation used and should not be relied upon. Modifying constant data through non-const pointers is considered a bad practice and should be avoided. The correct approach is to use a non-const reference or create a non-const copy of the data you intend to modify.

The above is the detailed content of Why Does Modifying a Constant through a Non-const Pointer Produce Undefined Behavior?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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