Page 42 of 62
SBasic User's Manual SBasic Version 2.7 Page 42
Printed: December 5, 1999
Subroutines, GOSUB, and USR()
SBasic supports the traditional Basic concept of subroutines. A
subroutine is a block of SBasic statements that can be invoked, or
called, from elsewhere in the SBasic program. After these statements
complete execution, control returns to the calling section.
A subroutine contains a line label marking the start of the
subroutine, and at least one RETURN statement, which transfers control
back to the calling section.
The calling section of SBasic code invokes, or calls, a subroutine by
means of the GOSUB statement.
Example:
main:
do ' start of an endless loop
gosub foo ' call subroutine FOO
loop ' loop forever
foo: ' start of subroutine FOO
a = a + 1 ' increment A
return ' return to caller
This example, while not very useful, shows how a subroutine is invoked
and how it is defined. Note that you can use a GOSUB to a subroutine
before that subroutine is defined in your code.
Note that code inside a subroutine has full access to all variables
defined with the DECLARE statement. Changes made to a variable from
inside a subroutine remain in effect when control returns from that
subroutine.
All GOSUBs push a return address onto the target's return stack.
SBasic's data stack resides a fixed distance below the return stack.
Excessive nesting of GOSUBs could clobber values on the data stack.
The address of the subroutine invoked must be either a label or a
variable; you may not use algebraic expressions or functions as
addresses for a GOSUB statement.
GOSUBs may pass one or more arguments to the called subroutine. Your
code should include the arguments after the name of the subroutine
invoked. For example:
main:
do ' start an endless loop
gosub foo, 3, j ' call FOO with two arguments
loop ' loop forever