on...gosub Statement

The on... gosub statement transfers control to a local subroutine designated by a specific statement label according to the positional value returned by the expression. The syntax can also be specified as on...go sub...(allowing a space between go and sub).

Syntax

on exp gosub statement.label{,

statement.label...}

 

on exp gosub statement.label,...,

statement.label,

statement.label

Parameter(s)

exp

Numeric value that corresponds to the position of comma-separated statement.labels.

Description

If required, the exp is truncated to an integer. The program executes the local subroutine at the statement.label that corresponds to exp. For example, if the expression evaluates to 1, the first subroutine is executed. If the exp evaluates to a number less than 1, or to a number greater than the number of statement labels, no action is taken. Execution continues at the first executable statement following the on...gosub.

The local subroutine must be terminated with a return statement. At the end of the subroutine, the program returns to the statement following the on...gosub statement.

For ease of reading, the on...gosub statement.label list can be spread over multiple lines if each continued line is terminated with a , (comma).

Example(s)

If response is 1, this branches to subroutine 8000. If it is 2, it branches to subroutine 9000. If it is 3, it branches to subroutine 9500.

loop

print ’1) doit 2) printit 3) deleteit’

input response

until num(response) do repeat

if response >=1 and response <= 3 then

on response gosub 8000,9000,9500

end

In this example, the result of the index() function is used as the index expression to determine which subroutine is called. If the response is a, then subroutine doit is called, and so on.

print ’a) doit b) printit c) deleteit’

input response,1

on index(’abc’,response,1) gosub doit,printit,deleteit

When the value of the index expression has a large number of possible branches, readability is improved by using the multiple line syntax.

on response gosub 10,20,30,40,50,60,

70,80,90,100,110,120,130

See Also

on...goto Statement, return Statement, Statement Labels, Statements and Functions