GOSUB Statement

The GOSUB statement transfers control to the line with the specified statement label, where the program sequentially proceeds until it reaches a RETURN statement.

Format

GOSUB label

ON expr GOSUB label1 label2 ...

Parameter(s)

label…

Statement labels as described in Format, Data and Expressions.

expr

An expression evaluating to a numeric value.

Description

The GOSUB statement has two forms of execution: the direct branch to a specified subroutine, and the computed branch to one of several subroutines.

When the first form is used, program control is transferred to the line starting with the specified label. Once a RETURN statement is encountered, program control transfers back to the statement following the corresponding GOSUB in the main program. The set of statements confined between the branch label and the RETURN statement constitutes an internal subroutine.

The ON...GOSUB syntax variation, or computed GOSUB, may be used to call different subroutines according to the value of expr. expr is evaluated and truncated into an integer n, and the subroutine beginning with the nth label on the statement line is given control of the program. If expr evaluates to a number less than 1 or greater than the number of statement labels listed, no action is taken.

The colon is optional in the statement label reference. Furthermore, the statement label may be anywhere in the program; that is, it may either precede or follow the referencing GOSUB statement. If the specified statement label is not found, an error message is printed at compile time.

Example

This example shows how a GOSUB statement may be used to allow the user some control of program execution.

   PRINT  "WOULD YOU LIKE THE RESULTS? (Y OR N)":

   INPUT ANSWER

   IF ANSWER = "Y" THEN GOSUB CALC

* CONTROL RETURNS HERE AFTER CALC

      .

      .

      .

CALC:  *CONTROL TRANSFERS HERE IF ANSWER  =  Y

      .

      .

      .

   RETURN

The next example shows how a Computed GOSUB statement may be used in a menu-driven program. Note that the input is tested for a proper value, and execution is suspended until a reasonable response is supplied.

PRINT "CHOOSE A MENU (1, 2 OR 3)":

INPUT MENU

* CONFIRM THAT RESPONSE IS VALID

LOOP

WHILE MENU < 1 OR  MENU > 3 DO

      PRINT "ILLEGAL INPUT."

   PRINT "CHOOSE A MENU (1, 2 OR 3)":

   INPUT MENU

REPEAT

* BRANCH TO REQUESTED MENU

ON MENU GOSUB MENU1, MENU2, MENU3

*  CONTROL RETURNS HERE AFTER SUBROUTINE

.

.

.

STOP

MENU1:   *  CONTROL TRANSFERS HERE IF MENU 1 IS CHOSEN

   .

   .

   .

   RETURN

MENU2:   *  CONTROL TRANSFERS HERE IF  MENU 2 IS CHOSEN

   .

   .

   .

   RETURN

MENU3:   *  CONTROL TRANSFERS HERE IF MENU 3 IS CHOSEN

   .

   .

   .

   RETURN

See Also

Statement and Function Reference