Home > database >  Why a reference declaration influences my pointer?
Why a reference declaration influences my pointer?

Time:07-19

Case 1

#include <iostream>
using namespace std;
int main() {
    int n = 1;
    // int & r = n;
    int * p;
    cout << &n << endl;
    cout << p << endl;
    return 0;
}

Output 1

0x7fffffffdc94
0

Case 2

#include <iostream>
using namespace std;
int main() {
    int n = 1;
    int & r = n;
    int * p;
    cout << &n << endl;
    cout << p << endl;
    return 0;
}

Output 2

0x7fffffffdc8c
0x7fffffffdd90

In Output 2, the pointer p just pointed to the address followed int n. Shouldn't an unintialized pointer point to some random places? Why adding a reference declaration influences the address of p pointed to?

CodePudding user response:

Shouldn't an unintialized pointer point to some random places?

No, an uninitialized pointer points nowhere. It has an indeterminate value. Trying to read and/or print this indeterminate pointer value as you are doing in

cout << p << endl;

has undefined behavior. That means there is no guarantee whatsoever what will happen, whether there will be output or not or whatever the output will be.

Therefore, there is no guarantee that changing any other part of the code doesn't influence the output you will get. And there is also no guarantee that the output will be consistent in any way, even between runs of the same compiled program or multiple compilations of the same code.


Practically, the most likely behavior is that the compiler will emit instructions that will simply print the value of whatever memory was reserved on the stack for the pointer. If there wasn't anything there before, it will likely result in a zero value. If there was something there before it will give you that unrelated value.

None of this is guaranteed however. The compiler can also just substitute the read of the pointer value with whatever suits it or e.g. recognize that reading the value has undefined behavior and that it may therefore remove the output statement since it can not be ever reached in a valid program.

  • Related