GATE / CS ARCHIVE

GATE CSE 1997 / QUESTION 10(b)

Trace reference-parameter recursion

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

GATE 1997, Q10(b) 2 marks · Descriptive
Report issue

Functions & Parameter Passing

Question 10(b), GATE 1997: Consider this pseudo-Pascal program, where z is global:
program what;
var z:integer;
procedure recur(x);
begin
  if x<=40 then begin
    x:=x+z;
    recur(x);
    z:=x+10
  end
end;
begin
  z:=10;
  recur(z);
  writeln(z)
end.
If x is passed by reference, what is printed?
Question 10(b), GATE 1997: Consider this pseudo-Pascal program, where z is global:
program what;
var z:integer;
procedure recur(x);
begin
  if x<=40 then begin
    x:=x+z;
    recur(x);
    z:=x+10
  end
end;
begin
  z:=10;
  recur(z);
  writeln(z)
end.
If x is passed by reference, what is printed?
Tap to enlarge
Answer & solution

Answer: 110. (no official key was published)

Step through it (11 steps)

The main program calls recur(z), so its reference parameter x is another name for the global variable z. Passing that reference onward as recur(x) keeps the same alias in every activation. There are not separate saved integer values of x in the suspended calls.

Initially x=z=10. The first body executes x:=x+z, doubling the shared variable to 20. The next call doubles it to 40. Because the guard is x≤40, the call seeing 40 also executes the body and doubles it to 80. The next call sees 80 and returns immediately. Thus four activations exist, three with a pending final assignment.

On unwinding, every z:=x+10 reads the current shared value, because x aliases z. The three pending assignments make the values 80→90→100→110. The program consequently prints 110.

It would be incorrect to use the descent values 10,20,40 as saved local copies during unwinding: that is pass-by-value behavior. It would also be incorrect to stop at 80, since the three assignments following recursive calls still have to execute. The example shows why mutation of a reference argument can interact unexpectedly with a global variable naming the same storage location.

Original paper, page 7