How does a variable at the same address produce 2 different values?

Consider this:

#include <iostream> using namespace std; int main(void) { const int a1 = 40; const int* b1 = &a1; char* c1 = (char *)(b1); *c1 = 'A'; int *t = (int*)c1; cout << a1 << " " << *t << endl; cout << &a1 << " " << t << endl; return 0; } 

The output for this is:

 40 65 0xbfacbe8c 0xbfacbe8c 

It almost seems impossible to me if the compiler does not do the optimization. How?

+6
source share
4 answers

This is undefined behavior , you change a constant variable so that you do not have expectations about the results. We can see this by going to the draft standard section of C ++ 7.1.6.1 Cv classifiers, which states:

[...] any attempt to change the const object during its lifetime (3.8) leads to 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 

The standard definition of undefined behavior in section 1.3.24 gives the following possible behaviors:

[...] Acceptable undefined behavior varies from completely ignoring the situation with unpredictable results, maintaining during a translation or program execution in a documented manner specific to the environment (with or without a diagnostic message), to complete the translation or execution (with a diagnostic message) . [...]

+14
source

There is undefined behavior in your code because you are modifying a persistent object. Anything can happen, nothing is impossible.

+4
source

When you qualify them with const variables, the compiler can take a few things and generate the code, this works great if you respect this convention and don't break it. When you break it, you get undefined behavior.

Note that when const is removed, it works as expected; here is a living example .

+2
source

As explained by others, changing the value of const leads to undefined behavior, and you don’t need to say anything else - any result is possible, including complete nonsense or failure.

If you are interested in how this particular result happened, it is almost certainly related to optimization. Since you defined a as const , the compiler can substitute the value 40 that you assigned to it when you want; after all, its value cannot change, right? This is useful if you use a to determine the size of the array, for example. Even in gcc, which has an extension for arrays of variable size, it is easier for the compiler to allocate an array with a constant size. Once optimization exists, it is probably applied sequentially.

0
source

All Articles