mirror of
https://github.com/QB64Official/qb64.git
synced 2024-08-22 09:05:08 +00:00
77 lines
2.3 KiB
Text
77 lines
2.3 KiB
Text
[[GOSUB]] sends the program flow to a sub procedure identified by a line number or label.
|
|
|
|
|
|
{{PageSyntax}}
|
|
: GOSUB {{{Parameter|lineNumber}}|{{Parameter|label}}}
|
|
|
|
|
|
{{PageDescription}}
|
|
* 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.
|
|
<!-- needs clarification: * 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 located outside the procedure.
|
|
|
|
|
|
==QBasic/QuickBASIC==
|
|
* 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.
|
|
|
|
|
|
{{PageExamples}}
|
|
''Example:'' Simple usage of GOSUB
|
|
{{CodeStart}}
|
|
{{Cl|PRINT}} "1. It goes to the subroutine."
|
|
{{Cl|GOSUB}} subroutine
|
|
{{Cl|PRINT}} "3. And it returns."
|
|
{{Cl|END}}
|
|
|
|
subroutine:
|
|
{{Cl|PRINT}} "2. It is at the subroutine."
|
|
{{Cl|RETURN}}
|
|
|
|
{{CodeEnd}}
|
|
{{small|Code by Cyperium}}
|
|
{{OutputStart}}
|
|
1. It goes to the subroutine.
|
|
2. It is at the subroutine.
|
|
3. And it returns.
|
|
{{OutputEnd}}
|
|
|
|
|
|
|
|
|
|
''Example:'' What happens if two GOSUB executes then two RETURN's?
|
|
{{CodeStart}}
|
|
start:
|
|
|
|
a = a + 1
|
|
{{Cl|IF...THEN|IF}} a = 1 {{Cl|THEN}} {{Cl|GOSUB}} here: {{Cl|PRINT}} "It returned to IF a = 1": {{Cl|END}}
|
|
{{Cl|IF...THEN|IF}} a = 2 {{Cl|THEN}} {{Cl|GOSUB}} there: {{Cl|PRINT}} "It returned to IF a = 2": {{Cl|RETURN}}
|
|
|
|
|
|
|
|
here:
|
|
{{Cl|PRINT}} "It went here."
|
|
{{Cl|GOTO}} start
|
|
|
|
there:
|
|
{{Cl|PRINT}} "It went there."
|
|
{{Cl|RETURN}}
|
|
{{CodeEnd}}
|
|
{{small|Code by Cyperium}}
|
|
{{OutputStart}}
|
|
It went here.
|
|
It went there.
|
|
It returned to IF a = 2
|
|
It returned to IF a = 1
|
|
{{OutputEnd}}
|
|
''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.
|
|
|
|
|
|
{{PageSeeAlso}}
|
|
* [[ON...GOSUB]]
|
|
* [[ON...GOTO]], [[GOTO]]
|
|
* [[ON ERROR]], [[RESUME]]
|
|
* [[ON TIMER (n)]]
|
|
* [[Line number]]
|
|
|
|
|
|
{{PageNavigation}}
|