ON GOSUB statement

Purpose

Call one of several subroutines according to the value of a numeric expression.

Syntax

ON n GOSUB {label | line_number} [, {label | line_number}] ...

Remarks

n is a numeric expression ranging from 1 to 255, and each label or line number identifies a statement to branch to.  When this statement is encountered, the nth label in the list is branched to; for example, if n equals 4, the fourth label in the list receives control.  If n is less than one or greater than the number of labels, no branch occurs, and PowerBASIC continues execution with the statement immediately following the ON GOSUB statement.

Each subroutine should end with RETURN, which causes execution to resume with the statement immediately following the ON GOSUB statement.  ON GOSUB can only branch to labels or line numbers that have the same scope as the ON GOSUB statement.

The SELECT and IF blocks also perform multiple branching and are more flexible than ON GOSUB.

Note that ON GOSUB (and ON GOTO) have been internally optimized to produce greater run-time performance than was possible with previous versions of PowerBASIC.

See also

GOSUB, FUNCTION/END FUNCTION, IF block, ON GOTO, RETURN, SELECT, SUB/END SUB

Example

FOR I& = 1 TO 3

  ON I& GOSUB OneHandler, TwoHandler, ThreeHandler

NEXT I&

 

OneHandler:

  Message$ = "Handler number" + STR$(I&)

  RETURN

 

TwoHandler:

  Message$ = "Handler number" + STR$(I&)

  RETURN

 

ThreeHandler:

  Message$ = "Handler number" + STR$(I&)

  RETURN

Result

Handler number 1

Handler number 2

Handler number 3