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



{{PageSyntax}}
:: 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 &quot;Out of Stack Errors&quot; 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}} &quot;1. It goes to the subroutine.&quot;
{{Cl|GOSUB}} subroutine
{{Cl|PRINT}} &quot;3. And it returns.&quot;
{{Cl|END}}

subroutine:
{{Cl|PRINT}} &quot;2. It is at the subroutine.&quot;
{{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}} &quot;It returned to IF a = 1&quot;: {{Cl|END}} 
{{Cl|IF...THEN|IF}} a = 2 {{Cl|THEN}} {{Cl|GOSUB}} there: {{Cl|PRINT}} &quot;It returned to IF a = 2&quot;: {{Cl|RETURN}}
 


here: 
{{Cl|PRINT}} &quot;It went here.&quot; 
{{Cl|GOTO}} start

there: 
{{Cl|PRINT}} &quot;It went there.&quot; 
{{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 &quot;here:&quot;, then it uses GOTO to go back to &quot;start:&quot;. a is increased by one so when a = 2 it uses GOSUB to go to &quot;there:&quot;, 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:'' 
* [[ON...GOSUB]]
* [[ON...GOTO]], [[GOTO]]
* [[ON ERROR]], [[RESUME]] {{text|{Error handlers only)}} 
* [[ON TIMER (n)]]
* [[Line number]] {{text|(removal program)}}


{{PageNavigation}}