c++functionreferencepass-by-reference

Can someone explain to me why after this function is called a becomes 2 instead of 3 or 4?


#include <iostream>
using namespace std;
void f(int &x, int &y)
{
    x = 1;
    x = x + y;
}
int main()
{
    int a = 3;
    f(a, a);
    cout<<a;
    return 0;
}

I found this function somewhere and the question was what the value of a is after f(a, a) is called, when a is 3. I thought it should be between 3 and 4 but it somehow gives 2, which I don't understand. Can someone explain why this happens, and how do such functions even work to begin with? Like it's so confusing, since it looks like a is both 3 and 4 after the function.


Solution

  • You may use several references to the same object to change it. For example

    int a;
    int &x = a;
    int &y = a;
    
    x = 1;
    x = x + y;
    

    As the both references x and y point to (are aliases of) the same variable a then after this statement

    x = 1;
    

    a becomes equal to 1. And in the next statement

    x = x + y;
    

    in fact you have

    a = a + a;
    

    As a result a will be equal to 2.