+ 2
Hey friends! Please explain me this code and say why output is 478?
#include <iostream> using namespace std; 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; return 0; } //output :478
1 Antwort
+ 6
function x accepts two parameters a and b, both are passed by reference, meaning, assignment to either a and/or b will reflect actual value of a and/or b in the function caller scope.
(In main)
a = 2, b = 7
Calling x, passing 'a' as 1st & 2nd argument
(In func x)
a = 3 // here a = 3 (it was 2)
b = 4 // here a = 4 (it was 3)
NOTE: in main, we passed 'a' in place of parameter 'b', so here, again, a is assigned new value (4).
Return a + b (4 + 4) = 8
(Exit function x)
(Edit: Accidentally submitted)
(Back in main)
a = 4
b = 7 (no change)
c = 8 (returned from function x)
cout << a << b << c;
Output: 478
Hth, cmiiw