BASIC stamp manual v2.2
5: BASIC Stamp Command Reference – GOSUB
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 209
GOSUB
BS1 BS2 BS2e BS2sx BS2p BS2pe BS2px
GOSUB Address
Function
Store the address of the next instruction after GOSUB, then go to the point
in the program specified by Address; with the intention of returning to the
stored address.
• Address is a label that specifies where to go.
Quick Facts
Table 5.29: GOSUB Quick Facts.
BS1 All BS2 Models
Max. GOSUBs
per program
16 255
Max. nested
GOSUBs
4 4
Related
Commands
GOTO ON...GOSUB and GOTO
Explanation
GOSUB is a close relative of GOTO, in fact, its name means, "GO to a
SUBroutine". When a PBASIC program reaches a GOSUB, the program
executes the code beginning at the specified address label. Unlike GOTO,
GOSUB also stores the address of the instruction immediately following
itself. When the program encounters a RETURN command, it interprets it
to mean, “go to the instruction that follows the most recent GOSUB.” In
other words, a GOSUB makes the BASIC Stamp do a similar operation as
you do when you see a table or figure reference in this manual; 1) you
remember where you are, 2) you go to the table or figure and read the
information there, and 3) when you've reached the end of it, you "return"
to the place you were reading originally.
GOSUB is mainly used to execute the same piece of code from multiple
locations. If you have, for example, a block of three lines of code that need
to be run from 10 different locations in your entire program you could
simply copy and paste those three lines to each of those 10 locations. This
would amount to a total of 30 lines of repetitive code (and extra space
wasted in the program memory). A better solution is to place those three
lines in a separate routine, complete with it's own label and followed by a
GOSUB CAN SAVE EEPROM
(PROGRAM) SPACE.
1
A
ll
2