GOSUB - QB64 Wiki

GOSUB

From QB64 Wiki

Jump to: navigation, search

GOSUB sends the program to a sub program that uses a line number or label.


Syntax:

GOSUB label


  • Label is any line number or line label designated with a colon after it. Don't use the colon in the call.
  • RETURN at the end of the procedure returns to the next code after the original call. END or SYSTEM can also be used to end program.
  • A procedure loop may be used to return automatically instead of using return.
  • GOSUB and GOTO can be used within SUB or FUNCTION procedures, but cannot refer to a label not in the procedure itself.
  • Note: 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.


Code Examples:

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

Code by Cyperium

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 a = 1 THEN GOSUB here: PRINT "It returned to IF a = 1": END IF 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

Code by Cyperium

It went here. It went there. It returned to IF a = 2 It returned to IF a = 1

Explanation: When a = 1 it uses GOSUB to go to "here:", then it uses GOTO to go back to "start:". a is increased by one so when a = 2 it uses GOSUB to go to "there:", and uses RETURN to go the last GOSUB (which is on the IF a = 2 line), it then encounters another RETURN which makes it return to the first GOSUB call we used on the IF a = 1 line.



See also:



Navigation:
Go to Keyword Reference - Alphabetical
Go to Keyword Reference - By usage
Go to Main WIKI Page
Views
Personal tools