Review of subroutine
 

Subroutines (a.k.a.: functions, procedures, sub-programs, methods):

  • Other names for subroutine are:  

    • Procedure
    • Function and
    • Method

  • Subroutine is a program unit that can be called (= invoked) from anywhere in the computer program

  • Control flow of a subroutine call:

      • When a subroutine is called (= invoked), the program execution is transfered to the first instruction of the subroutine

      • Program execution will continue in the subroutine until the subroutine returns

      • When the subroutine returns, the program execution will continue at the statement after the subroutine call

Review of subroutine
 

Control flow of subroutine calls:

The arrows show you the program execution order (= control flow) )

Important observation

Important observation:

  • The function return order is always the reverse order of the function call order

Example:

 If:                         Call order:
      A( ) calls B( )
      B( ) calls C( )          A --> B --> C --> D
      C( ) calls D( )

 Then:                       Return order:
      D( ) returns to C( )
      C( ) returns to B( )     D --> C --> B --> A
      B( ) returns to A( )
   

I.e.: function call/return order is: Last In First Out (LIFO) !!

Programming principle: pick your data structure right !
 

Important programming principle:

  • Always select a data structure that matches the behavior of your program

    (This is the most efficient solution !!!)

 

Therefore, the most efficient implementation for the function call mechanism, will use:

  • A stack

    Because a stack provide LIFO access to the saved information

    The LIFO ordering matches the function call/return ordering !!!

What will be discussed next ?
 

Order of discussion:

  1. Why the assembler instructions that you have learned so far cannot be used to implement subroutine call + return

  2. Introduce 3 new assembler instructions to implement subroutine call + return:

      1. bl (branch and link)

      2. push (push a value onto the system stack)

      3. pop (pop a value off the system stack)        

  3. Learn how to:

    • Pass parameters to a function/subroutine

    • Pass a return value to the caller

    • Create and destroy local variables in a function/subroutine call