I stumbled on this piece of code earlier (don't remember where, so I duplicated it here). It outputs 6. What I don't understand is how. Can anyone explain please? Thank you. I realize a pointer must be created somewhere, but it can't be "r" because we're doing r*=2.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
using std::cout;
using std::endl;
void f(int &r);
int main()
{
int i = 3;
f(i);
cout << i << endl;
return 0;
}
void f(int &r)
{
r = r*2;
}
From what I read the tutorial just explains what happens when you use it, but not why it happens. Is it something like (from the example above) in function f, the value 3 with the alias i also gets the alias r, instead of a new variable being created for r in pass by value?
For standard types the overhead of copying the value is negligible. Though, your impression seems to be right, indeed. A reference is made to the inputted variable. This means that the function gets access to the variable you pass into it. It also means that you don't have to copy a lot of values (which is specifically helpful for vectors, strings and other containers or classes). When you understand how to use references and pass by reference, I suggest you check out the part in the tutorial where constant references are explained.