2 2 points Consider the following C program where i means i
Solution
int bar(int &i) // A function bar, which takes an integer i passed by reference as input, and will return an integer.
{
i = i * 3; //i value is tripled.
return 2 + i; //The tripled value + 2 is returned.
}
void foo1()
{
int x = 3, y = 5, sum; //All these are local variables.
sum = x; //sum is also initialized with 3.
sum = sum + bar(x); //sum = 3 + bar(3) ==> sum = 3 + the returned value, i.e., 3*3 + 2 i.e., 11.
//So, sum = 3 + 11 = 14.
//Note that x value is updated to 9, after the call to bar().
}
void foo2()
{
int x = 3, y = 5, sum; //All these are local variables.
sum = bar(y); //sum = bar(y) ==> sum = the returned value, i.e., 3 * 5 + 2 i.e., 17.
//So, sum = 17.
//Note that y value is updated to 15, after the call to bar().
sum = sum + x; //sum = sum + 3 ==> sum = 17 + 3 = 20.
}
So, the answers are:
a. What is the value of sum at the end of the function foo1? Briefly explain why?
As explained in the function, at the end of function foo1, sum value is 14.
b. What is the value of sum at the end of the function foo2? Briefly explain why?
As explained in the function, at the end of function foo2, sum value is 20.
