[Prev] [Next] [Contents] [Commodore] [New] [Search] [Home]

GOSUB

TYPE: Statement
FORMAT: GOSUB <line number>

Action: This is a specialized form of the GOTO statement, with one important difference: GOSUB remembers where it came from. When the RETURN statement (different from the <RETURN> key on the keyboard) is reached in the program, the program jumps back to the statement immediately following the original GOSUB statement.

The major use of a subroutine (GOSUB really means GO to a SUBroutine) is when a small section of program is used by different sections of the program. By using subroutines rather than repeating the same lines over and over at different places in the program, you can save lots of program space. In this way, GOSUB is similar to DEF FN. DEF FN lets you save space when using a formula, while GOSUB saves space when using a several- line routine. Here is an inefficient program that doesn't use GOSUB:

   100 PRINT "THIS PROGRAM PRINTS"
   110 FOR L = 1 TO 500:NEXT
   120 PRINT "SLOWLY ON THE SCREEN"
   130 FOR L = 1 TO 500:NEXT
   140 PRINT "USING A SIMPLE LOOP"
   150 FOR L = 1 TO 500:NEXT
   160 PRINT "AS A TIME DELAY."
   170 FOR L = 1 TO 500:NEXT

Here is the same program using GOSUB:

   100 PRINT "THIS PROGRAM PRINTS"
   110 GOSUB 200
   120 PRINT "SLOWLY ON THE SCREEN"
   130 GOSUB 200
   140 PRINT "USING A SIMPLE LOOP"
   150 GOSUB 200
   160 PRINT "AS A TIME DELAY."
   170 GOSUB 200
   180 END
   200 FOR L = 1 TO 500 NEXT
   210 RETURN

[Prev] [Next] [Contents] [Commodore] [New] [Search] [Home]
This page has been created by Sami Rautiainen.
Read the small print. Last updated November 14, 1998.