Page 96 - Introduction to Microcontrollers Architecture, Programming, and Interfacing of The Motorola 68HC12
P. 96

3.4 Stack Index Addressing, Reentrancy and Recursion                 73






















                       Figure 3.12. Subroutine to Compute n! Recursively

            Although recursive subroutines implement a scientist's induction mechanism, they
        are not always useful. Consider the alternative in Figure 3.13 that uses a loop. The
        alternative is significantly more efficient. The recursive solution uses the hardware stack
        as a counter, pushing a 2-byte return address and 2-byte saved parameter value each time
        it calls itself to reduce its parameter by 1. If n is 5, this subroutine uses up 20 bytes of
        stack storage. This is not efficient. But there are efficient recursive subroutines,
        especially for following linked list data structures, as we will see in Chapter 9.
            A subroutine is reentrant if it can be stopped, for instance because of an interrupt,
        and then resumed, and it will get the same result as if it were not stopped, even though
        the interrupt handler might call this subroutine during its execution. Also, a time-sharing
        computer uses interrupts to switch between tasks or threads that share a computer.
        Reentrant subroutines can be used by each task or thread, without concern that, when a
        thread or task is stopped during execution of the subroutine, another thread will execute
        the subroutine. The subroutine in Figure 3.14 is nonreentrant, and following it is a
        reentrant subroutine; both clear five bytes beginning at location $824.

















                        Figure 3.13. Subroutine to Compute n! in a Loop
   91   92   93   94   95   96   97   98   99   100   101