Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading