Home > Backend Development > C++ > body text

Why does modifying a `const` value through a non-const pointer lead to undefined behavior but still print different values for the pointer and the original variable?

Barbara Streisand
Release: 2024-10-28 04:47:02
Original
226 people have browsed it

Why does modifying a `const` value through a non-const pointer lead to undefined behavior but still print different values for the pointer and the original variable?

Modifying a const through a Non-const Pointer

Consider the following code:

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

int* w = (int*) &e;          // (1) cast to remove const-ness
*w = 5;                        // (2)

cout << *w << endl;            // (3) outputs 5
cout << e << endl;             // (4) outputs 2

cout << "w = " << w << endl;   // (5) w points to the address of e
cout << "&e = " << &e << endl;</code>
Copy after login

In (1), w points to the address of e. In (2), that value is changed to 5. However, when the values of *w and e are displayed, their values are different. But if you print the pointer w and the address of e, they have the same value.

How come e still contains 2, even if it was changed to 5? Were they stored in a separate location? Or a temporary? But how come the value pointed by w is still the address of e?

Answer

Once you modify a const value, you enter undefined behavior territory. However, to speculate:

  • (3) and (4): *w is evaluated at runtime, while e is treated as a compile-time constant. Hence, the different printed values.

The above is the detailed content of Why does modifying a `const` value through a non-const pointer lead to undefined behavior but still print different values for the pointer and the original variable?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!