Can someone please explain why the output of the below code snippet is 20 ?
int i = 10;
cout << i << endl;
int &r = i;
r = 20;
cout << i << endl;
First, variable i stores the integer value 10
Then 10 is displayed.
Then the address of r (memory location of r) is set to i which is 10 And then r becomes 20 But why i changes to 20 as well?
The integer content of r has changed, not address of it (memory location of it).
Thanks,
The variable r is a refernce to i, it’s like a pointer except that instead of saying *r = 20;
you just say r = 20; and that changes the value of r.