| Introduction | MTB Statements | File System | Compiler | Applications | Reference Guide | Index |
| Language Structure | Data Division | I/O Format Division | Procedure Division | Mnemonics |
| Syntax: | GOSUB statement-label | ||||
| Discussion: |
The GOSUB statement directs program control to the specified
statement-label and places the next executable address in a
subroutine stack.
Subsequent execution of a RETURN statement will direct program control to the saved address (the next statement following the original GOSUB statement). The statement-label defines the beginning of a "subroutine," even though the program lines are contained in the main MTB program itself. Subroutines themselves may invoke other subroutines -- these are called "nested subroutines." Subroutines may be nested up to 16 levels. Attempting to nest beyond this depth will result in a "GOSUB STACK OVERFLOW" exception. | ||||
| Example 1: |
Processing continues in the subroutine until the program encounters the RETURN statement. At this point, control is transferred back to the main section of the program (to the statement immediately after the GOSUB 1000 statement). The STOP statement is included in the main section of the program to prevent program flow from entering the subroutine without using the GOSUB statement. | ||||
| Example 2: |
In subroutine ONE, there is a call to a nested subroutine called TWO. From this subroutine, there is a further call to a nested subroutine called THREE. Notice that all of the subroutines end with a RETURN statement, which directs control to the statement following the most recent GOSUB call. | ||||