GOSUB statement

Syntax

GOSUB statement.label [ : ]
GO SUB statement.label [ : ]

Description

Use the GOSUB statement to transfer program control to an internal subroutine referenced by statement.label. A colon ( : ) is optional in GOSUB statements, even though it is required after nonnumeric statement labels at the beginning of program lines.

Use the RETURN statement at the end of the internal subroutine referenced by the GOSUB statement, to transfer program control to the statement following the GOSUB statement.

Use the RETURN TO statement at the end of an internal subroutine to transfer control to a location in the program other than the line following the GOSUB statement. In this case, use statement.label to refer to the target location.

Be careful with the RETURN TO statement, because all other GOSUBs or CALLs active when the GOSUB is executed remain active, and errors can result.

A program can call a subroutine any number of times. A subroutine can also be called from within another subroutine; this process is called nesting subroutines. You can nest up to 256 GOSUB calls.

Subroutines can appear anywhere in the program but should be readily distinguishable from the main program. To prevent inadvertent entry into the subroutine, precede it with a STOP statement, END, or GOTO statement that directs program control around the subroutine.

Example

VAR='ABKL1234'
FOR X=1 TO LEN(VAR)
   Y=VAR[X,1]
   GOSUB 100
NEXT X
STOP
100*
IF Y MATCHES '1N' THEN RETURN TO 200
PRINT 'ALPHA CHARACTER IN POSITION ',X
RETURN
200*
PRINT 'NUMERIC CHARACTER IN POSITION ',X
STOP

This is the program output:

ALPHA CHARACTER IN POSITION  1
ALPHA CHARACTER IN POSITION  2
ALPHA CHARACTER IN POSITION  3
ALPHA CHARACTER IN POSITION  4
NUMERIC CHARACTER IN POSITION          5