BASIC stamp manual v2.2

GOSUB – BASIC Stamp Command Reference
Page 210 BASIC Stamp Syntax and Reference Manual 2.2 www.parallax.com
RETURN command, then just use a GOSUB command at each of the 10
locations to access it. This technique can save a lot of program space.
Try the example below:
Main:
GOSUB Hello
DEBUG "How are you?"
END
Hello:
DEBUG "Hello, my friend!", CR
RETURN
The above code will start out by GOSUB'ing to the section of code
beginning with the label Hello. It will print "Hello, my friend!" on the
screen then RETURN to the line after the GOSUB… which prints "How are
you?" and ENDs. Note: colons ( : ) are placed after labels, as in “ “Main: “
and “Hello:” but the colon is not used on references to these labels such as
in the “GOSUB Hello” line.
There's another interesting lesson here; what would happen if we removed
the END command from this example? Since the BASIC Stamp reads the
code from left to right / top to bottom (like the English language) once it
had returned to and run the "How are you?" line, it would naturally "fall
into" the Hello routine again. Additionally, at the end of the Hello routine,
it would see the RETURN again (although it didn't GOSUB to that routine
this time) and because there wasn't a previous place to return to, the
BASIC Stamp will start the entire program over again. This would cause
an endless loop. The important thing to remember here is to always make
sure your program doesn't allow itself to "fall into" a subroutine.
A limited number of GOSUBs are allowed per program (as shown in Table
5.29), and they may be nested only four levels deep. In other words, the
subroutine that’s the destination of a GOSUB can contain a GOSUB to
another subroutine, and so on, to a maximum depth (total number of
GOSUBS before the first RETURN) of four. Any deeper, and the program
will "forget" its way back to the starting point (the instruction following
the very first GOSUB).
When GOSUBS are nested, each RETURN takes the program back to the
instruction after the most-recent GOSUB. As is mentioned above, if the
WATCH OUT FOR SUBROUTINES THAT
YOUR PROGRAM CAN
"FALL INTO."
GOSUB
LIMITATIONS.
NOTE: On the BS1, a RETURN
without a GOSUB will return the
program to the last GOSUB (or will end
the program if no GOSUB was
executed).
1