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