void addOne(int &y)
{
y = y + 1;
}
int main()
{
int x = 5;
std::cout << "x = " << x << '\n';
addOne(x);
std::cout << "x = " << x << '\n';
return 0;
}
Sorry if this is a basic question. But why does y = y + 1 is 6?
void addOne(int &y)
{
y = y + 1;
}
int main()
{
int x = 5;
std::cout << "x = " << x << '\n';
addOne(x);
std::cout << "x = " << x << '\n';
return 0;
}
Sorry if this is a basic question. But why does y = y + 1 is 6?
What might help, initially, is to think of references as syntactic sugar for pointers.
Consider the following:
int main() {
int x = 5;
int *px = &x;
*px = 8;
cout << x << endl;
return 0;
}
This prints out 8
, as you would expect. (If you didn't expect that then it might be worth reading an introduction to pointers before tackling references.)
A reference variable, then, can be thought of as a pointer variable whose syntax is that of a regular variable. The following is equivalent to the previous example:
int main() {
int x = 5;
int &rx = x;
rx = 8;
cout << x << endl;
return 0;
}
That is, rx
becomes a reference to x
, and thus whenever you change rx
, you change x
as well, because both names refer to the same thing... or in other words, rx
is bound to a memory location, not a value, and setting rx
changes what is at that memory location.
In a sense, rx
is sort of invisible - it doesn't have an existence of its own, it only exists in terms of what x
is (which is why you have to initialize a reference when it's declared, i.e. you can't do int ℞
in a function and leave it hanging).
So when you have:
void addOne(int &y)
{
y = y + 1;
}
This is a function whose parameter is a reference to what is passed in... and so when the parameter reference is changed, that which the reference refers to is also changed.
And so when you call it like this:
int main()
{
int x = 5;
std::cout << "x = " << x << '\n';
addOne(x);
std::cout << "x = " << x << '\n';
return 0;
}
This calls addOne
with x
, thus initializing the int &
reference y
to x
, and so whenever y
is changed, x
is changed... and so x
changes from 5
to 5 + 1
, i.e. 6
.
You can think of it as equivalent to the following:
void addOne(int *py)
{
*py = *py + 1;
}
int main()
{
int x = 5;
std::cout << "x = " << x << '\n';
addOne(&x);
std::cout << "x = " << x << '\n';
return 0;
}
To see why you'd use a reference vs. a pointer, see this question.
A reference is not an independent variable, you should consider it to literally be another. So when you pass x to function addOne, the reference called y literally becomes x (how this works behind the screens is less important right now).
So when you increase y by one, what you are really doing is increasing x. That's why x is 6, after the call to addOne.