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 cha开发者_运维技巧nged, 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.
When you make a reference it's almost like a pointer so when you can changed r you actually changed what r was pointing to which is also i.
Actually to be more precise the reference is not a pointer or an address, it is the object. At least in c++ world.
Think about it as:
int i = 10;
cout << i << endl;
int *p = &i;
*p = 20;
cout << i << endl;
This is basically what's happening behind the scenes
精彩评论