"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 Constant through a Non-const Pointer Produce Undefined Behavior?

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

Published on 2024-11-07
Browse:690

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

const int e = 2;

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

After making this modification, you observe that:

  • Displaying the value pointed to by w (cout w
  • However, displaying the value of e (*cout

You further notice that the address pointed to by w is the same as the address of e (cout cout 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.

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