GOSUB - mkilgore/QB64pe GitHub Wiki
GOSUB sends the program flow to a sub procedure identified by a line number or label.
- GOSUB {lineNumber|label}
- Use RETURN in a sub procedure to return to the next line of code after the original GOSUB call. END or SYSTEM can also be used to end program.
- GOSUB and GOTO can be used within SUB or FUNCTION procedures, but cannot refer to a label located outside the procedure.
- Too many GOSUBs without a RETURN can eventually cause "Out of Stack Errors" in QBasic as each GOSUB uses memory to store the location to return to. Each RETURN frees the memory of the GOSUB it returns to.
Example: Simple usage of GOSUB
PRINT "1. It goes to the subroutine." GOSUB subroutine PRINT "3. And it returns." END subroutine: PRINT "2. It is at the subroutine." RETURN |
1. It goes to the subroutine. 2. It is at the subroutine. 3. And it returns. |
Example: What happens if two GOSUB executes then two RETURN's?
start: a = a + 1 IF...THEN a = 1 THEN GOSUB here: PRINT "It returned to IF a = 1": END IF...THEN a = 2 THEN GOSUB there: PRINT "It returned to IF a = 2": RETURN here: PRINT "It went here." GOTO start there: PRINT "It went there." RETURN |
It went here. It went there. It returned to IF a = 2 It returned to IF a = 1 |
Navigation:
Go to Keyword Reference - Alphabetical
Go to Keyword Reference - By usage
Go to Main WIKI Page