简体   繁体   中英

C++ Pointer Confusion

Please Explain the following code

#include <iostream>

using namespace std;

int main()
{
    const int x = 10;
    int * ptr;
    ptr = (int *)( &x );    //make the pointer to constant int*
    *ptr = 8;               //change the value of the constant using the pointer.
    //here is the real surprising part
    cout<<"x: "<<x<<endl;          //prints 10, means value is not changed
    cout<<"*ptr: "<<*ptr<<endl;    //prints 8, means value is changed
    cout<<"ptr: "<<(int)ptr<<endl; //prints some address lets say 0xfadc02
    cout<<"&x: "<<(int)&x<<endl;   //prints the same address, i.e. 0xfadc02
    //This means that x resides at the same location ptr points to yet 
    //two different values are printed, I cant understand this.

    return 0;
}
*ptr = 8;

This line causes undefined behavior because you are modifying the value of a const qualified object. Once you have undefined behavior anything can happen and it is not possible to reason about the behaviour of the program.

Since x is a const int , the compiler will most likely, in the places where you use x , directly substitute the value that you've initialized with (where possible). So the line in your source code:

cout<<"x: "<<x<<endl;

will be replaced by this at compile time:

cout<<"x: "<<10<<endl;

That's why you still see 10 printed.

But as Charles explained, the behaviour is undefined, so anything could happen with code like this.

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