next up previous contents
Next: Exercises on the Up: CHAPTER.3: PROCEDURES AND Previous: Implicit uses of

Example: implicit uses of the stack when running "perim"

The previous section listed five ways in which Pop-11 programs implicitly use the stack. We can now combine points 1, 2, 3, 4, and 5, and look closely at the implicit stack instructions when Pop-11 runs the procedure perim, defined in Chapter 1.

First a reminder of its definition in chapter 1:

    define perim(len, breadth) -> result;
        (len + breadth) * 2 -> result
    enddefine;
Assuming the definition has already been compiled, we can step through what happens when it is obeyed in the following instruction (declare the variable num, compute the perimeter of a 3 by 4 room and assign the result to num):

    vars num;
    perim(3, 4) -> num;
This implicitly "expands" into the following Pop-11 virtual machine instructions:

STEP    What happens                   VM instruction

(a)    put 3 on the stack              (i.e. PUSH 3),
(b)    put 4 on the stack              (i.e. PUSH 4),
(c)    run perim                       (i.e. CALL perim),
        this will do various things and leave a result on the stack
(d)    move the top of stack to num    (i.e. POP num)
We can look more closely at step (c), i.e. what happens when the procedure runs. Look at the definition, from chapter 1:

    define perim(len, breadth) -> result;
        (len + breadth) * 2 -> result
    enddefine;
When this runs, with 3 and 4 on the stack, as in step (c) above it does the following:

STEP     What happens                             VM instruction

(ca)     move top of stack (i.e. 4) to breadth    (POP breadth)
(cb)     move top of stack (i.e. 3) to len        (POP len)
(cc)     copy value of len (i.e. 3) to stack      (PUSH len)
(cd)     copy value of breadth (i.e. 4) to stack  (PUSH breadth)
(ce)     run +                                    (CALL +)
            (which takes 3 and 4 off the stack and puts back 7)
(cf)     put 2 on the stack                       (PUSH 2)
(cg)     Run the multiplication procedure         (CALL *)
            (this takes 7 and 2 off and puts back 14)
(ch)     Move top of stack (14) to result         (POP result)
(ci)     Finally, because result is an output
        local, its value is put on the stack     (PUSH result)
It is not absolutely essential to understand such details of implicit stack manipulation on order to develop Pop-11 programs, but it will make many things clearer and will help with more advanced programming. For practice try the following exercises:



Aaron Sloman
Fri Jan 2 03:17:44 GMT 1998