ON GOSUB Statement
Transfers control to an internal subroutine determined by the current value of a given expression.
Syntax
ON expression GOSUB statementLabel{,statementLabel}...
Syntax Elements
expression Any DataBasic expression that evaluates to an integer value.
statementLabel The label of the statement to which control is to be transferred. Can be any numeric or alphanumeric label.
Operation
The ON GOSUB statement evaluates expression, which must evaluate to an integer. If expression evaluates to 1, control is transferred to the first statement label. If expression evaluates to 2, control is transferred to the second statement label, and so on.
If expression evaluates to less than one, the following message is displayed and the branch is taken to the first statement label:
[B22] BRANCH INDEX OF x IS ILLEGAL;
BRANCH TAKEN TO FIRST STATEMENT-LABEL!
If expression evaluates to an integer greater than the number of statement labels in the list, the following message is displayed and the branch is taken to the last statement label:
[B23] BRANCH INDEX OF x EXCEEDS NUMBER OF STATEMENT-LABELS;
BRANCH TAKEN TO LAST STATEMENT-LABEL!
If any of the statement labels in the list refers to a label that does not exist, the program will not compile and an error message is printed.
Note
This behaviour can be changed with the ONGO compatibility option.
Return from Subroutine
The RETURN statement returns control to the statement immediately following the ON GOSUB statement that called the subroutine.
The RETURN TO statement returns control to a specific statement specified by statement-label.
See Also
ON GOTO statement, GOSUB statement.
Examples
ON X+Y GOSUB 101, 117, 103, 216
PRINT Y
Transfers control to the internal subroutine with statement label 101, 117, 103 or 216, depending on whether the value of X+Y is 1 (or less than 1), 2, 3 or 4 (or more than 4). Y is printed when control returns from the subroutines.
ON Z GOSUB 20, 20, 29
INPUT A
Transfers control to label 20 if Z <= 2, or to label 29 in all other cases. The system prompts for input when control returns via a RETURN statement.
IF T GE 1 AND T LE 3 THEN
ON T GOSUB 110, 120, 130
END
The IF statement guarantees that T is in the range of the computed GOSUB statement, so that a 'branch index' message is not displayed.