This is because whenever a function or any other compound statement is entered, a new block of memory is allocated to hold its automatic variables. These blocks are allocated as a stack of blocks. When the compound statement completes, either by executing a return statement or by reaching the end of its statements, its block is popped off and returned to the pool of available memory.
This has important implications for recursive functions. When a function calls itself, new copies of its automatic variables are created. The values in the block for the older, calling instance of the function are kept safely in a block below the newly created one on the stack. The current instance of the procedure updates its own versions of the variables and, when it finishes, the calling instance resumes with its versions of these variables still set to the values they had before the call.
In the recursive pocket calculator program the variables Operator and Answer retain their values in this way while nested sub-expressions are evaluated by recursive calls.
Parameter values passed to functions are kept in the block for the function to which they are passed and so their values are lost at the return from that function.
Exercises on this section.
Back to Contents page.