Assume that the program ‘𝑃′ is implementing parameter passing with ‘call by…
2016
Assume that the program ‘𝑃′ is implementing parameter passing with ‘call by reference’. What will be printed by following print statements in 𝑃?
Program P
{
x=10;
y=3;
funb(y,x,x)
print x;
print y;
}
funb (x,y,z)
{
y=y+4;
z=x+y+z;
}
- A.
10, 7
- B.
31, 3
- C.
10, 3
- D.
31, 7
Attempted by 221 students.
Show answer & explanation
Correct answer: B
Key idea: Call by reference makes formal parameters aliases of the actual variables, so assignments to formals change the caller's variables.
Initial values: x = 10, y = 3.
Parameter bindings for funb(y, x, x): the function's first formal parameter aliases the caller's y; the second formal parameter aliases the caller's x; the third formal parameter also aliases the caller's x. Thus the second and third formals refer to the same caller variable.
Execute y = y + 4 inside the function: this updates the variable aliased by the function's y formal (which is caller x). So caller x becomes 10 + 4 = 14.
Execute z = x + y + z: evaluate using current aliases—function x = caller y = 3, function y = caller x = 14, function z = caller x = 14. So z := 3 + 14 + 14 = 31, and this assignment updates caller x to 31.
After returning from the function, the caller's variables are x = 31 and y = 3.
Answer: 31, 3