GOSUB CommandSummaryTransfers execution to a subroutine. Syntax
Remarks and Examples
A subroutine is a section of code that is identified by a line number or line label, and which ends with a RETURN statement. To call a subroutine, specify the GOSUB statement, followed by the line number or line label of the subroutine. The GOSUB statement will cause the program execution to jump to the line number or line label, and commands will be executed until a RETURN statement is encountered, at which point execution will transfer back to the statement immediately following the GOSUB statement. The following is an example of a subroutine being defined and called in a line-numbered program: 100 PRINT "Hello" 110 Name$ = "Alice" 120 GOSUB 2000 130 Name$ = "Bob" 140 GOSUB 2000 150 END 2000 REM This is a subroutine 2010 PRINT "Hi" 2020 PRINT "Your name is "; Name$ 2030 GOSUB 3000 2040 RETURN 3000 REM This is another subroutine 3010 PRINT "Tralala" 3020 RETURN Running this program gives the following output: Hi Your name is Alice Tralala Hi Your name is Bob Tralala The following is an example of a similar subroutine being defined in a program that uses line labels instead of line numbers: Main:
Name$ = "Alice"
GOSUB SayMyName
Name$ = "Bob"
GOSUB SayMyName
END
SayMyName:
PRINT "Hi"
PRINT "Your name is "; Name$
GOSUB SayTralala
RETURN
SayTralala:
PRINT "Tralala"
RETURN
Running this program gives the following output: Hi Your name is Alice Tralala Hi Your name is Bob Tralala Subroutines do not offer any formal support for parameters, though global variables can be used to similar effect as the examples above illustrate. Caution must be taken when using variables in subroutines, because it is easy to unintentionally modify values being used elsewhere in the program. For example: 100 X% = 1 110 WHILE X% <= 5 120 GOSUB 500 130 X% = X% + 1 140 WEND 150 END 500 PRINT X% 510 X% = 100 520 RETURN This program gives the result: 1 The WHILE-WEND loop may appear to be counting from 1 to 5, but the modification of X% in the subroutine causes the loop to end because the new value of 100 is greater than the loop end limit of 5. Procedures and functions can define local variables (using the LOCAL statement), which can avoid such problems. See also: FUNCTION, LOCAL, PROCEDURE, RETURN Copyright 2006-2012, Kevin Matz, All Rights Reserved. |
|