Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

integer pointer to constant integer

Tags:

c++

I'd like to know what is happening internally and its relation to values displayed. The code is:

# include <iostream>

int main(){
    using namespace std;
    const int a = 10;

    int* p = &a;  //When compiling it generates warning "initialization from int* to 
              //const int* discard const -- but no error is generated

    cout << &a <<"\t" << p <<endl; //output: 0x246ff08 0x246ff08 (same values)
    cout << a << "\t" << *p << endl; //output: 10 10

    //Now..
    *p = 11;
    cout << &a <<"\t" << p <<endl; //output: 0x246ff08 0x246ff08 (essentially, 
                               //same values and same as above, but..)
    cout << a << "\t" << *p << endl; //output: 10 11

    return 0;
}

QUESTION: If p = address-of-a, how come a=10, but *p = (goto address of a and read value in the memory location) = 11?

like image 435
user3272925 Avatar asked Dec 06 '22 03:12

user3272925


2 Answers

 cout << a << "\t" << *p << endl; //output: 10 11

You lied to the compiler and it got its revenge.

With:

const int a = 10;

you promised you'll never modify a object.

like image 82
ouah Avatar answered Dec 08 '22 16:12

ouah


You promised not to modify a, and the compiler believed you. So it decided to optimise away the reading of a, because it trusted you. You broke your promise.

Having said that, a real C++ compiler won't compile your code because int* p = &a is illegal. So perhaps you are lying to us as well. Or perhaps you need to get a real C++ compiler.

like image 23
David Heffernan Avatar answered Dec 08 '22 17:12

David Heffernan