Integer pointer to a constant integer

I would like to know what is going on inside and its relation to the displayed values. Code:

# 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 did you get a = 10, but * p = (goto address a and read in the memory location) = 11?

+4
source share
4 answers
 cout << a << "\t" << *p << endl; //output: 10 11

You lied to the compiler, and he took revenge.

FROM

const int a = 10;

You promised that you would never modify the object a.

+8
source

You promised not to change a, and the compiler believed you. So he decided to optimize the reading abecause he trusted you. You have broken your promise.

, ++ , int* p = &a . , , . , , ++.

+5

Like Oua, the compiler took revenge

but I do not agree with you that he makes no mistake

const int a = 10;

int* p = &a;

You cannot assign a constant to a non-constant pointer.

+2
source

In C, this is undefined behavior . In C ++, this will not compile. It was repeated by David Heffernan several times, but it is worth repeating. Here is the error you should get in a modern compiler:

main.cpp:7:10: error: cannot initialize a variable of type 'int *' with an rvalue of type 'const int *'

    int* p = &a;  //When compiling it generates warning "initialization from int* to 
0
source

Source: https://habr.com/ru/post/1525330/


All Articles