MC logo

Parameter Passing and Scope Problem Solution


Parameter Passing and Scope Problem

Here is what the program outputs:
  1. As it stands, the program prints:

    30
    77
    30
    2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 
    10 8 30
    

  2. If we replace the header of Wumpus with PROCEDURE Wumpus(var ana, susan: integer; sara: integer); we get:

    29
    77
    29
    2 3 4 5 5 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 
    10 8 29
    

  3. What is the output if we assume (contrary to Pascal rules) that the parameters are passed by name?

    29
    77
    29
    2 3 4 5 6 7 8 9 10 10 12 13 14 15 16 17 18 19 20 21 
    10 13 29
    

    The rule is to substitute the parameter with the argument text. So, the in the first execution, ana := susan + 4 becomes lucretia := curly + 4. But be sure to keep track of your larrys. When we pass Wumpus(larry, bill[larry], larry+3), each larry bound to an argument is the larry in Bumpus, so larry := sara; become larry := larry + 3;, but they are different larrys.

  4. If we assume static scope, we get:

    30
    44
    30
    2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 
    10 20 30
    

    The only change from regular execution is that larry in Wumpus will refer to the larry in Bumpus instead of the one in Fred. Hence the the printout of larry in Bumpus changes to 44 (since it was changed by Wumpus rather than the other one), and the value remains 20 for the final printout, since the global is no longer changed by Wumpus.

Here is the program for reference:

PROGRAM Fred(input, output);
    VAR
        moe, larry, curly: integer;

    PROCEDURE Wumpus(ana, susan, sara: integer);
        BEGIN
            ana := susan + 4;
            larry := sara;
            susan := susan - 1;
            writeln(curly)
        END;

    PROCEDURE Bumpus;
        VAR
            larry, lucretia, i: integer;
            bill: array[1..20] OF integer;
        BEGIN
            FOR i := 1 TO 20 DO bill[i] := i + 1;

            larry := 77;
            lucretia := 44;
            Wumpus(lucretia, curly, lucretia);
            writeln(larry);

            larry := 5;
            Wumpus(larry, bill[larry], larry + 3);

            FOR i := 1 TO 20 DO write(bill[i], ' ');
            writeln;
        END;

    BEGIN
        moe := 10;
        larry := 20;
        curly := 30;
        Bumpus;
        writeln(moe, ' ', larry, ' ', curly)
    END.

<<