Specifications
BASIC Stamp II
Page 266 • BASIC Stamp Programming Manual 1.8 • Parallax, Inc.
Gosub
GOSUB
addressLabel
Store the address of the next instruction after Gosub, then go to the
point in the program specified by addressLabel.
•
AddressLabel
is a label that specifies where to go.
Explanation
Gosub is a close relative of Goto. After Gosub, the program executes
code beginning at the specified address label. (See the entry on Goto
for more information on assigning address labels) Unlike Goto, Gosub
also stores the address of the instruction immediately following itself.
When the program encounters a Return instruction, it interprets it to
mean “go to the instruction that follows the most recent Gosub.”
Up to 255 Gosubs are allowed per program, but they may be nested
only four 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 never find 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.
If a series of instructions is used at more than one point in your pro-
gram, you can conserve program memory by turning those instruc-
tions into a subroutine. Then, wherever you would have had to insert
that code, you can simply write Gosub label (where label is the name of
your subroutine). Writing subroutines is like adding new commands
to PBASIC.
You can avoid a potential bug in using subroutines by making sure
that your program cannot wander into them without executing a Gosub.
In the demo program, what would happen if the stop instruction were
removed? After the loop finished, execution would continue in
pickAnumber. When it reached Return, the program would jump back
into the middle of the For...Next loop because this was the last return
address assigned. The For...Next loop would execute indefinitely.










