+ 4

Pls explain how it will work?

int x(int &a,int &b) { a=3; b=4; return a+b; }; int main () { int a=2; int b=7; int c=x(a,a); cout<<a<<b<<c; } output is coming out to be 478.

9th Jan 2018, 7:03 PM
Himani
3 Answers
+ 4
you write numbers 4 7 and 8 next to each other without any space, that's why it's 478 function takes references as arguments - to the same variable (in main identified as 'a') you assign values 3 and then 4, only the later is kept. So a is 4 and c is 4+4=8 b is 7 and not changed later
9th Jan 2018, 8:04 PM
michal
+ 4
@michal. Thanks â˜ș let me tell now what I have understood correct me if I'm wrong function x will take the reference of a only. now when 3 is assigned to a it will also make changes in actual parameter a which will now be holding 3 . then when 4 is assigned to b , since b also has the reference of a so now , actual parameter a will be holding value 4 so when we return a+b it will return 8 because now basically formal parameters a& b both are holding the value 4. so values in actual parameters will be a=4,b=7 and c=8 so output will be 478
9th Jan 2018, 8:52 PM
Himani
+ 2
yes, you are right
10th Jan 2018, 3:22 PM
michal