0
Help why function return answer unpredictable
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; //478 }
2 Answers
+ 2
Because you pass "a" as both arguments, b = 4 affects a, setting its value to 4. The function returns a + b, so in this case 4 + 4 = 8 => c equals 8. Since you passed a by reference, it keeps the new value => a equals 4. b is not affected by the function because you didn't pass it as an argument.
So you output 4(a) b(7) c(8).
Keep in mind "b" in the function is not automatically the "b" from main(), but rather a local variable.
0
evry time i dry run this program i think answer will be 477 or 377 but it returns 478 but why