why is the output for the following snippet of code 20 30 40 40 30 20 61 60 20 2
ID: 3550210 • Letter: W
Question
why is the output for the following snippet of code
20 30 40
40 30 20
61 60 20
20 30 61 ?
---------------------------------------...
int foo(int &a, int b, int &c)
{
cout << a << " " << b << " " << c << " ";
a += 1+c;
b *= 2;
cout << a << " " << b << " " << c << " ";
return a;
}
int main ( )
{
int a=20, b=30, c=40;
cout << a << " " << b << " " << c << " ";
foo(c,b,a);
cout << a << " " << b << " " << c << " " << " ";
return 0;
}
Explanation / Answer
1st line of output i.e 20 30 40 is due to the cout in the main before foo(c,b,a);
cout << a << " " << b << " " << c << " ";
2nd line of output i.e 40 30 20comprises of value of c b a as in function foo(c,b,a ) is called in this order
3rd line of output i.e 61 60 20 is due to
a += 1+c;
b *= 2;
above statement .But as we see in the function definition that 1st and third argument i.e c and a is called by reference,the changes in the function will be reflected in main.but for b it wont happen
hence in main after the execution of above statement c=61, a=20, b=30
in 4th line of output i.e 20 30 61 we see that it is due to cout in main so main value of a,b,c is printed
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.