1

I don't quite understand why the output on this is 10 10 if ri is a reference to i...

int i, &ri = i;
i = 5; 
ri = 10;
std::cout << i << " " << ri << std::endl;

Could someone clear this up for me?

Similarly,

int i = 0, &r1 = i;
double d = 1, &r2 = d;

r2 = r1;
std::cout << r2;  // output 0
i = r2;
std::cout << i;  // output 0
r1 = d;
std::cout << r1; // output 0

If i = r2 and r2 is a refrence to d when d = 1, why isn't the ouput 1? Also, when r1 = d, why isn't the output 1 as well?

Tyler
  • 1,933
  • 5
  • 18
  • 23

2 Answers2

0

A reference is just like addressing the original item. Like *(& some_variable)

In your code therefore the line

r2 = r1;

sets the value of d to the value of i which is 0.

from then on all values are 0

if you replace the names r1 with ref_i and r2 to ref_d it will make sense.

Try it here:

http://ideone.com/SHxQLN

int i = 0, &ref_i = i;
double d = 1, &ref_d = d;

ref_d = ref_i;       // <<-------------------- Put value of i into d
std::cout << ref_d; 

i = ref_d;
std::cout << i;

ref_i = d;
std::cout << ref_i;  
Preet Sangha
  • 64,563
  • 18
  • 145
  • 216
  • Thank you! That site is pretty useful! – Tyler Oct 03 '13 at 03:51
  • The really important thing to take away from here is that code that has good naming conventions will make your algorithms much easier to write, understand, debug and thus lowers the cost of maintenance. – Preet Sangha Oct 03 '13 at 03:54
0

Think of reference as an alias (an alternative name) for an object. Whatever you do with a reference you do with the object it refers to. Here:

int i, &ri = i;

you say that ri is another name for i. Thus, here:

i = 5;

you set i = 5, and here

ri = 10;

you set i = 10.

cpp
  • 3,743
  • 3
  • 24
  • 38