#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.
You may use several references to the same object to change it. For example
As the both references
xandypoint to (are aliases of) the same variableathen after this statementabecomes equal to1. And in the next statementin fact you have
As a result
awill be equal to2.