V1[]
GOSUB
and RETURN
are commands which allow use of subroutines in Petit Computer BASIC.
GOSUB
must be followed by a label. When a GOSUB
is encountered while running the program, that point in the program is pushed onto a 'call stack', then execution of the program continues from the label (like GOTO
). When a RETURN
is encountered, the last value added to the 'call stack' is removed, and execution continues from that point again (i.e. the location of the corresponding GOSUB
).
Essentially, the idea is that you can create a small program (a "subroutine"), put a label at the beginning of it, and put RETURN
at the end of it. You can execute this subroutine by using GOSUB
with that label. If you have a task that needs to be performed many times, this can save a lot of typing and make your code more robust to change. Even if a section of code is used only once, using subroutines to separate different tasks can help make your program tidy and more easily understood and maintained.
The 'call stack' has a maximum depth of 255. This means that from the start of the program you can run 255 consecutive GOSUB
s, but the next one will generate an Out of memory
error. If the system encounters a RETURN
when the call stack is empty, it generates a RETURN without GOSUB
error.
The GOSUB
stack memory is shared with the FOR
stack memory... so, if the very start of a program is a FOR
loop, you can only run 254 consecutive GOSUB
s within that loop before getting an Out of memory
error. Any additions to the FOR
stack made in a subroutine, that are not removed in the normal way by the execution of a NEXT
ending the loop, are removed by the RETURN
. So, a single RETURN
can free up two or more spaces in the stack memory. In contrast, additions to the call stack made during a FOR
loop are not removed by a NEXT
.
GOSUB
is not allowed at the interactive command-line; this generates a Syntax error
.
V2[]
GOSUB
and RETURN
in SmileBasic V2 are the same as in SmileBasic V1, except GOSUB
does not have to be follwed by a label: it may instead be followed by a string value representing a label. The first character of the string must be "@
", or the program will generate a Syntax error
.
V3[]
No information on SmileBasic V3.