Table of Contents

ON-GOSUB

Flow control statement that selects a subroutine to jump to according to the value of a variable or numeric expression

Implemented by: decbasic, Applesoft, TI994, CBM, Atari, msatari, trs80, trscolor, colormc, GWBASIC, MSX, bwbasic, bw32, ABasiC, FreeBASIC, Gambas, ugBASIC

With variations:

Also written as:

Usage

ON-GOSUB is a "syntactic sugar" found in many BASICs that can replace a number of IF-THEN statements at once, making it specially useful for the so common option menus in character-mode interfaces.

After the ON particle, there must be a numeric variable or formula that may evaluate 1, 2, 3 and so forth. Then comes the GOSUB keyword followed by multiple, comma-separated line numbers or labels corresponding to the entry point of different subroutines where the program flow will jump to, according to the value.

10 INPUT "PRESS 1 FOR THE MONEY, 2 FOR THE SHOW, 3 TO GET READY"; V
20 ON V GOSUB 300, 600, 1000

When each subroutine finds it RETURN statement, program flow is resumed at the statement after the one with ON-GOSUB.

In most BASICs, there will be no jump if the variable or expression evaluates to 0 or to a value greater than the number of subroutine identifiers in the list. A negative value will cause a runtime error in some implementations.

Variations

Not all of the old BASICs documentation is assertive on what happens when the variable or expression evaluates to 0.

Information is also scarce about negative values:

Instead of just flowing to the next program line if the value exceeds the number of subroutines, an error will happen on DEC BASIC-PLUS.

The value of the variable/expression usually may be a fractional number that will be forced into an integer value. If you don't do it explicitely, you can have some surprises within the subroutine list:

8-bit BASICs usually had a limit of 255 for the evaluated value, and a higher value would cause a runtime error. Anyway the user would probably be unable to enter 255 subroutine line numbers after GOSUB as it would exceed the maximum line length. In Microsoft's GW-BASIC and QBasic/QuickBASIC, the accepted value ranges from -32768 to 32767.

Comments

Similar keywords

In other languages...

ON-GOSUB is somewhat related to the switch…case structures of C and derived languages such as PHP and Java.

References