简体   繁体   中英

Little problem with pointers and constants in C++

Can you explain this behaviour to me, pls? Here the code:

int* b = new int;
const int MAX_AGE = 90;
b = (int*)&MAX_AGE;
std::cout << b << std::endl;
std::cout << &MAX_AGE << std::endl;
std::cout << *b << std::endl;
std::cout << MAX_AGE << std::endl;
std::cout << "........." << std::endl;
*b = 2; 
std::cout << *b << std::endl; // HERE I get 2, that's ok
std::cout << MAX_AGE << std::endl; // HERE I still get 90, why?
std::cout << b << std::endl; 
std::cout << &MAX_AGE << std::endl; 

The problem is that you lied to your compiler, and compilers are pretty good at exacting revenge on people who lie to them.

Specifically, on this line you told the compiler that MAX_AGE is changeable:

b = (int*)&MAX_AGE;

This is a lie, because you declared MAX_AGE to be a const . What happens next is called undefined behavior (UB) : the compiler is free to produce any results, including complete nonsense, after your code triggers UB.

In your case, however, there is a pretty good explanation of what gets printed: knowing that MAX_AGE is another name for 90 , the compiler has optimized std::cout << MAX_AGE << std::endl; to print 90 , without looking up its value from memory.

MAX_AGE is declared as const int . With your c-style cast you remove constness and then proceed to modify a const value. This is UB.

This is a prime example for why this is UB: Due to the constness of MAX_AGE the compiler knows that it won't change and can thus replace all occurences of it by the literal 90 .

const tells the compiler that the variable MAX_AGE should be stored in the write protected region of the respective segment in memory. Armed with this knowledge the compiler can obviate the need to repeatedly read the same memory location. In other words the compiler might cache the constant value. That is why you see MAX_AGE showing up with the original value.

Anyway as has been already mentioned you shouldn't be confusing the compiler with your actual intentions. If you intend to store a variable in a write protected region then you shouldn't be modifying it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM