Home

GOSUB

GOSUB is a control flow instruction found in many BASIC dialects. It transfers program execution to a subroutine located at a specified line number or label and, when the subroutine completes, returns to the statement immediately following the GOSUB via the RETURN command. The language generally implements this with a return stack that records the address to resume after each GOSUB call, allowing nested subroutines up to the interpreter’s limit.

In typical usage, a GOSUB 1000 would jump to line 1000. The subroutine runs and ends with

GOSUB does not provide formal parameter passing; any data required by the subroutine is usually accessed through

RETURN,
which
returns
control
to
the
line
after
the
original
GOSUB.
If
RETURN
is
executed
without
a
preceding
GOSUB,
or
if
the
program
falls
off
the
end
of
the
subroutine
without
returning,
a
runtime
error
or
a
mismatch
error
is
often
produced.
Some
dialects
distinguish
between
successful
returns
and
errors
with
messages
such
as
“RETURN
without
GOSUB.”
global
variables
or
by
setting
values
before
issuing
GOSUB.
This
can
lead
to
tighter
coupling
between
code
blocks.
Because
of
its
reliance
on
a
return
stack
and
potential
for
tangled
control
flow,
GOSUB
is
considered
less
structured
than
modern
function
or
procedure
calls
and
is
less
common
in
new
software.
Nevertheless,
it
remains
part
of
the
heritage
of
classic
BASIC
interpreters
and
is
still
supported
in
many
dialects
for
backward
compatibility.
Some
newer
BASICs
offer
line-numberless
forms
or
labels
for
subroutines,
but
traditional
GOSUB
primarily
uses
line
numbers.