# ON...GOSUB

{PBASIC 2.5}

ON...GOSUB Example

Syntax: ON Offset GOSUB Address1, Address2, ...AddressN

## Function

Store the address of the next instruction after ON..GOSUB, then go to the Address specified by offset (if in range) with the intention of returning to the stored address. If Offset-1 is greater than the number of elements in the address table, the program continues at the line following ON..GOSUB.

- Offset is a variable/constant/expression (0 - 255) that specifies the index of the address, in the list, to branch to (0 - N).
- Addresses are labels that specify where to go for a given Offset. ON...GOSUB will ignore any list entries beyond offset 255.

## Quick Facts

| BS2 Family
Limit of Address entries | 256
Maximum nested GOSUBs | 4
Maximum GOSUBs per Program | 255 (each ON...GOSUB counts as as a GOSUB regardless of number of address list entries)
Related Commands | BRANCH, GOSUB, GOTO, ON...GOTO

## Explanation

The ON...GOSUB instruction is useful when you want to write something like this:

      IF (value = 0) THEN GOSUB Case_0
      IF (value = 1) THEN GOSUB Case_1
      IF (value = 2) THEN GOSUB Case_2

You can use ON...GOSUB to organize this into a single statement:

      ON value GOSUB Case_0, Case_1, Case_2

This works exactly the same as the previous IF…THEN example. If the value isn't in range (in this case if value is greater than 2), ON...GOSUB does nothing and the program continues with the next instruction after ON.

Go to Welcome page

BASIC Stamp Help Version 2.5.4

Copyright © Parallax Inc.

8/8/2012