Calling Functions

All 8-bit devices use a hardware stack for function return addresses. The maximum depth of this stack varies from device to device.

Typically, call assembly instructions are used to transfer control to a C function when it is called. A call uses one level of hardware stack that is freed after the called routine executes a return or retlw instruction. Nested function calls will increase the stack usage of a program. If the hardware stack overflows, function return addresses will be overwritten and the code will eventually fail.

For PIC18 devices, a call instruction is the only way in which function calls are made, but for other 8-bit devices, the -mstackcall option, (see Stackcall Option), can controls how the compiler behaves when the compiler detects that the hardware stack might overflow due to too many nested calls. When this option is enabled, the compiler will, instead of issuing a warning, automatically swap to using a managed stack that involves the use of a lookup table and which does not require use of the hardware stack.

When the lookup method is being employed, a function is reached by a jump (not a call) directly to its address. Before this is done the address of a special “return” instruction (implemented as a jump instruction) is stored in a temporary location inside the called function. This return instruction will be able to return control back to the calling function.

This means of calling functions allows functions to be nested deeply without overflowing the limited stack available on Baseline and Mid-range devices; however, it does come at the expense of memory and program speed.