How is a variable at the same address producing 2 different values? [duplicate]

This is undefined behavior, you are modifying a const variable so you can have no expectation as to the results. We can see this by going to the draft C++ standard section 7.1.6.1 The cv-qualifiers paragraph 4 which says:

[…]any attempt to modify a const object during its lifetime (3.8) results in undefined behavior.

and even provides an example:

const int* ciq = new const int (3); // initialized as required
int* iq = const_cast<int*>(ciq); // cast required
*iq = 4; // undefined: modifies a const object

In the standard definition of undefined behaviour in section 1.3.24, gives the following possible behaviors:

[…] Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of
a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message). […]

Leave a Comment