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