0
#import<iostream>
using namespace std;
int main()
{
    //trying to test pointers & reference
    int x = 5;
    int y = 6;
    int *p;
    p = &y;
    *p = 10;
    int &r = x;
    cout<<"X reference\n"<<&r<<"\n"<<"value:"<<r<<"\n";
    r=y;
    cout<<"Y reference\n"<<&r<<"\n"<<"value:"<<r<<"\n";
}

In this code, I have assigned &r to x at first and then I have assigned r to y.

  1. What is the difference between assigning & r=x and r=y? Kindly help me out.
sabarish
  • 1,059
  • 1
  • 11
  • 14
  • You can't reseat references. That's the difference. And why is there `import` in your code? –  Nov 21 '14 at 01:41
  • Try also printing out `x` and `y` at the end of the program. – aschepler Nov 21 '14 at 01:41
  • r is alias to x. `&r = x` initializes the reference to be alias to x. Since r is alias to x now, `r=y` is same as `x=y`. – Marcin Nov 21 '14 at 01:42
  • @remyabel #import is a [Microsoft specific preprocessor directive](http://stackoverflow.com/a/172274/2705293). – jmstoker Nov 21 '14 at 02:08

2 Answers2

4

int &r = x;

defines a reference to int variable.

References cannot change what they reference after they are defined, so the line

r=y;

is assigning x the value that is stored in y. It does not make r start referencing y. Any assignment to or from r will be treated as if it was from x.

Another way to think about references is as if they are a pointer variable which you cannot change what is pointed to after it is initialized and any occurrence of their usage has an implicit dereference (*) operator.

mclaassen
  • 5,018
  • 4
  • 30
  • 52
0

int& r = x declares a reference to x, think about it as an alias. So if you further down the line modify x, it will be reflected in r, for example,

x = 10;
cout << r; // r is "updated" here, as it is a reference to `x`

will print 10.

On the other hand, the declaration int r = x just copies the value of x into r, then r is completely independent of x. So modifying x will have absolutely no effect on r.

In a sense, reference are "kind-of" syntactic sugar for pointers, although not really the same, as you cannot have an uninitialized reference.

vsoftco
  • 55,410
  • 12
  • 139
  • 252