GATE / CS ARCHIVE

GATE CSE 1996 / QUESTION 19(ii)

Value-result parameter copy-back

Programming in C · Functions & Parameter Passing · Full GATE CSE 1996 paper

GATE 1996, Q19(ii) Descriptive
Report issue

Functions & Parameter Passing

Question 19(ii), GATE 1996: Global b is set to 3 and test1(b) is called. Procedure test1(a) sets a=5, prints “point 1:” followed by a,b, calls test2, then prints “point 2:” followed by a,b. Procedure test2 sets the global b=10. After test1 returns, the main program prints “point 3:” followed by b. Assume the displayed lexical scope and determine the output with a passed by value-result (copy-in/copy-out).
Question 19(ii), GATE 1996: Global b is set to 3 and test1(b) is called. Procedure test1(a) sets a=5, prints “point 1:” followed by a,b, calls test2, then prints “point 2:” followed by a,b. Procedure test2 sets the global b=10. After test1 returns, the main program prints “point 3:” followed by b. Assume the displayed lexical scope and determine the output with a passed by value-result (copy-in/copy-out).
Question 19(ii), GATE 1996: Global b is set to 3 and test1(b) is called. Procedure test1(a) sets a=5, prints “point 1:” followed by a,b, calls test2, then prints “point 2:” followed by a,b. Procedure test2 sets the global b=10. After test1 returns, the main program prints “point 3:” followed by b. Assume the displayed lexical scope and determine the output with a passed by value-result (copy-in/copy-out).
Tap to enlarge
Answer & solution

Answer: point 1: 5 3; point 2: 5 10; point 3: 5. (no official key was published)

Value-result creates a separate local parameter cell. At entry to test1, the current actual value b=3 is copied into a. The assignment a:=5 changes only that private cell; the global b remains 3. Thus the first output is point 1: 5 3.

The call to test2 then assigns 10 to the global b. It does not refer to the private parameter a of its caller, so a stays 5. The second output is consequently point 2: 5 10. This is the observable difference from call-by-reference: a is not an alias for b during the call.

At normal return from test1, the result phase copies the final local a back to the original actual parameter location b. That overwrites test2's value 10 with 5. The main program therefore prints point 3: 5. The chronological storage states are (a,b)=(3,3) at entry, (5,3) after assigning a, (5,10) after test2, and b=5 after copy-out. No conflict among multiple value-result actuals arises because the procedure has just one parameter. If it were ordinary call-by-value instead, there would be no final copy-back and point 3 would show 10; the word “result” is essential.

Original paper, page 9