Home > front end >  I don't understand a part of the C code, can someone explain it?
I don't understand a part of the C code, can someone explain it?

Time:10-21

I was wondering if someone could explain why the f2(a,a); is 13 13 and not 12 12?

Does this have something to do with the & sign, if so what does it mean?

Thanks in advance!

#include <iostream>

using namespace std;

void f1 (int a, int b){
 a = 12; b = 13;
}
void f2 (int& a, int& b){
a = 12; b = 13;
}


int main()
{
 int a = 10; int b = 11;
 f1(a,b);
 cout << a << ' ' << b << ' ';
 f2(a,b);
 cout << a << ' ' << b << ' ';
 f2(a,a);
 cout << a << ' ' << b;

}

CodePudding user response:

In your call f2(a, a) both arguments refer to the same variable (a) (the ampersand means "reference") so that is all you are changing. The function first assign 12 to it, then you assign 13 to it - so that's the final value. The variable b in the main function is not changed by that function call and retains its value (13), so when you subsequently print a and b in main, you get 13 and 13.

CodePudding user response:

This function

void f2 (int& a, int& b){
a = 12; b = 13;
}

accepts its arguments by reference. So calling it like

f2(a,a);

the both parameters are references to the same object a.

At first this object was assigned with the value 12

a = 12;

and then reassigned with the value 13

b = 13;

So the resulting value of the referenced object a is 13.

To make it more clear you can imagine the function call and its definition the following way (I will rename the parameters as a1 and b1 to avoid name collision)

f2(a,a);

// ...

void f2 ( /* int& a1, int& b1 */ ){
    int &a1 = a;
    a1 = 12; 
    
    int &b1 = a;  
    b1 = 13;
}

So the object a is being changed through the reference to it a1 and b1.

That is you may declare several references to the same object and use the references in any order to change the referenced object. The object will contain the last value assigned to it through one of the references.

Pay attention to that before this call

f2(a,a);

there was the following call

f2(a,b);

that set the value of the variable b to 13.

So this statement after the above two calls

cout << a << ' ' << b;

outputs

13 13

CodePudding user response:

By assigning a to f2(a,a); as both parameters you are doing so as a reference parameter and your code is executed sequentially. So a is first given the value 12 (the value assigned to formal parameter a in the function) and then the same variable is given the value 13 (the value assigned to formal parameter b in the function). The variable b in the main part of your program was is 13 after the function call f2(a,b);.

  • Related