Recursive Calls

Recursive calls are allowed for subprocedures. A recursive call is one where procedure A calls itself or calls procedure B which then calls procedure A again. Each recursive call causes a new invocation of the procedure to be placed on the call stack. The new invocation has new storage for all data items in automatic storage, and that storage is unavailable to other invocations because it is local. (A data item that is defined in a subprocedure uses automatic storage unless the STATIC keyword is specified for the definition.) Note also that the automatic storage that is associated with earlier invocations is unaffected by later invocations. The new invocation uses the same static storage as the previous invocation, both the global static storage of the module, and the local static storage in the procedure.

Recursive calls are also allowed for programs whose main procedure is a linear-main procedure. A linear-main procedure can only be called through a program call, so when a linear-main procedure calls itself recursively, the program containing the linear-main procedure is called again. Otherwise, the behavior for a linear-main procedure calling itself recursively is the same as for an ordinary subprocedure calling itself recursively.

A cycle-main procedure that is on the call stack cannot be called until it returns to its caller. Therefore, be careful not to call a procedure that might call an already active cycle-main procedure.

Try to avoid situations that might inadvertently lead to recursive calls. For example, suppose there are three modules, as shown in Figure 1.

Figure 1. Three Modules, each with subprocedures
Three Modules, each with subprocedures

You are running a program where procedure A in module X calls procedure B in module Y. You are not aware of what procedure B does except that it processes some fields. Procedure B in turn calls procedure C, which in turn calls procedure A. Once procedure C calls procedure A, a recursive call has been made. The call stack sequence is shown in Figure 2. Note that the most recent call stack entry is at the bottom.

Figure 2. Recursive Call Stack To Be Avoided
Recursive Call Stack To Be Avoided

So while subprocedures can be called recursively, if you are not aware that recursion is occurring, you may exhaust system resources.


Unconditional recursive calls can lead to infinite recursion which leads to excessive use of system resources. Infinite recursion can be avoided with proper programming. In general, a proper recursive procedure begins with a test to determine if the desired result has been obtained. If it has been obtained, then the recursive procedure returns to the most recent caller.