UMBC CMSC 211 |
One of the most ingenious temporary uses of the stack is to call other subprocedures. In fact a procedure can call itself recursively, arbitrarily many times. The only thing to remember is the rule that a procedure must pop off everything (and only those things) that it put onto the stack. That way, the return address will be available in the right position when the ret instruction is executed. When a subprocedure is called within a subprocedure, the call and corresponding ret take care to keeping the stack tidy automatically.
Continuing this ingenious use, the subprocedure can use the stack for its local variables. Remember in C, the variables declared in the body of the function exist only while the function is being executed. When the control passes back to the caller, the local functions disappear. What happens is that the local variables are created on the stack below the return address (we must store in a register what the starting address of the local variables is) and then we can refer to the local variables as an offset from that start. This way when we have recursion, each instance of the function can only see its version of the local variables! We will get to see this better when we talk about addressing mode and arrays.