Living with the GOSUB Nesting Level Limitation

copyright, Peter H. Anderson, August, '98

Introduction

Recently, I was developing a program where my MAIN called A, which called B, which called C which called D which called E. Thus, my nesting level was five which exceeds the limitation of four. The net result was that on executing the RETURN in subroutine A my program went into "never never land" as the return address had been lost.

This is the first time the nesting limitation of four has limited me, and in searching for my problem, it was several hours before I consulted my Stamp manual and discovered what I should have known. The nesting level is limited to four. My point is that this is not something that one encounters all that often and in most cases, it can be solved by eliminating one or more levels of GOSUBs.

Solution

In this case, it simply wasn't convenient to do so and I was able to solve the problem with a GOTO in place of a GOSUB at the highest level and a conditional GOTO (that is, a BRANCH) in place of a RETURN to get me back to the MAIN.

Example.

LOG_DATA_RET_VAL VAR BYTE


MAIN:
	...

	LOG_DATA_RET_VAL = 0
	GOTO LOG_DATA		; this was previously a subroutine
LOG_DATA_RET_0:

	...
	...

LOG_DATA_RET_VAL = 1
	GOTO LOG_DATA		; this was previously a subroutine
LOG_DATA_RET_1:

	...
	...


LOG_DATA_RET_VAL = 2
	GOTO LOG_DATA		; this was previously a subroutine
LOG_DATA_RET_2:

	...
	...

'''''''''''

LOG_DATA:	' previously a subroutine

	' implementation which calls subroutines to a nested level of 4


	' the following is used in place of a return
	BRANCH LOG_DATA_RET_VAL, [LOG_DATA_RET_0, LOG_DATA_RET_1,
				  LOG_DATA_RET_2]
Note that each of the three "calls" to LOG_DATA are implemented by placing a unique value in variable LOG_DATA_RET_VAL so as to identify where the execution is to resume once LOG_DATA has been executed followed by a GOTO.

The "RETURN" has been replaced with a BRANCH which maps LOG_DTA_RET_VAL into the appropriate place to pick up program execution.

I can't say I all that thrilled with this approach, but it did resolve my stubborn problem.

Thoughts.

My suggestion to Stamp programmers is to use subroutines. Don't let this discussion give you the false impression that it is good programming to avoid an excessive number of calls to subroutines. But, keep the nesting level somewhere in the back of your mind. If you find your program inexplicably loosing its way, verify your nesting level does not exceed four.

If it does, take a good look to see if one level of nesting can be eliminated. If it is not convenient to do this, the above may be a solution.

However, good book-keeping is strongly suggested. Use meaningful labels for variables and program locations. The only penalty in using long label names is that they take more time to type and my experience in working with hundreds of students is spend the few minutes now in using meaningful labels or spend hours and hours later in debugging.