-1

I am trying to understand C++ reference variables. This link seems to indicate that a pointer can be reassigned while a reference should be assigned at initialization. difference between pointer and reference. I have the following code below. I have run it on a debian system. The output is also shown below. The output seems to indicate that reference can be reassigned as well.It would be great if someone could clarify.

#include <iostream>
using namespace std;

int main()
{
  int x = 5;
  int y = 6;
  int *p; 

  p = &x; 
  cout << "content of p " << *p << endl;

  p = &y; 
  cout << "content of p " << *p << endl;

  *p = 10; 
  cout << "content of p " << *p << endl;

  /*A reference must be assigned at initialization*/
  int &r = x;
  cout << "content of r " << r << endl;

  r = y;
  cout << "content of r " << r << endl;


  return 0;
}

Output

content of p 5
content of p 6
content of p 10
content of r 5
content of r 10
Community
  • 1
  • 1
liv2hak
  • 14,472
  • 53
  • 157
  • 270
  • 1
    A reference cannot be reassigned. If you think it can, then your test isn't thorough enough. – juanchopanza Feb 09 '16 at 20:57
  • 3
    Here `r = y;` does the same as `x = y;`. It does not assign the reference, it assigns the thing the reference refers to. – user253751 Feb 09 '16 at 20:58
  • Reference cannot be reassigned means `&r` will never change. `r` can change in case of reference-to-non-const. – LogicStuff Feb 09 '16 at 20:59
  • "content of p" is not correct. `p` holds a pointer, but the output is not displaying the value of the pointer; it's displaying the value that the pointer points at. Don't every lose track of the difference between a pointer and the thing it points at. – Pete Becker Feb 09 '16 at 20:59

1 Answers1

3

What you see here is the value being assigned to the variable referenced by the referencing variable.

In other words:
You did not assign new value to the referencing variable. You assigned a new value to the referenced variable.

user1708860
  • 1,683
  • 13
  • 32