MC logo

Problem 3.10: Pass-By-Name


CS 404: Solutions and Examples

This problem asks what values would be printed by an ALGOL program under various parameter-passing modes. Here is the program:
begin 
    integer i, j;
    integer array A[1:3];

    procedure P(x,y); integer x, y;
        begin
            y := 2;
            Print(x);
            i := 3;

            Print(x);
            Print(y);
        end

    A[1] := 7;
    A[2] := 11;
    A[3] := 13;
    i := 1;
    P(A[i], i);
    P(i, A[i])
end
The question has four parts:
  1. x and y are both passed by value. (This would require adding the declaration value x, y; at the start of procedure P.)

    The program prints 7, 7, 2, 3, 3, 2.

  2. x is passed by value and y is passed by name. (This would require adding the declaration value x; at the start of procedure P.)

    The program prints 7, 7, 3, 3, 3, 2. Also, at exit, A[3] has been changed to 2. The third number printed changes from 2 to 3 because the by-name binding of y to i means that the assignment i := 3 changes y to 3. The value of A[3] is changed by the assignment y := 2 on the second execution of P because y is bound by name to A[i].

  3. x is passed by name and y is passed by value. (This would require adding the declaration value y; at the start of procedure P.)

    The program prints 7, 13, 2, 3, 3, 2. The variables in the main program are not changed. The reason 13 (the second number) is printed is that the assignment i := 3 effects x, since it is bound by name to A[i]. Therefore the second Print(x) prints A[3].

  4. x and y are both passed by name, as written. The program prints 11, 13, 3, 3, 3, 2. Also, at exit, A[3] has been changed to 2. The reason 11 is printed the first time is that the assignment y := 2 actually changes i to 2. Then the following reference to x, which is A[i] by name, prints A[2], which contains 11.

<<
>>