0

why this output is 339 ??? #include<iostream> using namespace std; int x(int &a,int &b) { a=1; b=3; return a*b; } int main() { int a=3; int b=4; int c=x(b,b); cout<<a<<b<<c; }

1st Sep 2016, 4:36 AM
Lekhraj Singh
Lekhraj Singh - avatar
3 odpowiedzi
+ 2
int x(int &a,int &b) This function takes references as arguments, which means it can directly modify the content of the variables. So by passing b twice to it, here is what happens. local a and b inside the function are references to the global b a=1; // global b is set to 1 b=3; // global b is set to 3 (the previous line did nothing here) return a*b; // return (global b)*(global b) = 9 And the global b still holds 3 after the call since the value was directly modified. cout<<a<<b<<c thus prints 339. (Of course, when I say global b, I mean the b in the scope of main. It's not an actual global variable.)
1st Sep 2016, 7:07 AM
Zen
Zen - avatar
+ 1
when you call the function x you are reassigning the value of b so after calling function b becomes 3 hence answer is 339
1st Sep 2016, 6:07 AM
Kandarp Singh
Kandarp Singh - avatar
0
thanks Zen
1st Sep 2016, 9:03 AM
Lekhraj Singh
Lekhraj Singh - avatar