Skip to content

Language Reference, Flow Control GOSUB Statement

Andreas AFENTAKIS edited this page Oct 12, 2025 · 1 revision

FBASIC Flow Control: GOSUB and RETURN

The GOSUB (Go to Subroutine) and RETURN statements are used together to implement subroutines, which are reusable blocks of code designed to perform a specific task. This mechanism is key to writing modular and organized FBASIC programs.


Purpose

GOSUB transfers program execution to a specified Label (the start of the subroutine) while saving the current line of execution on an internal stack.

RETURN retrieves the last saved line number from the internal stack and transfers execution back to the statement immediately following the original GOSUB call.

Syntax

The GOSUB statement requires a defined Label name as its operand.

Part
GOSUB The required statement keyword that jumps to the subroutine and saves the return address on the internal stack.
LabelName The required name of the target Label where the subroutine begins.
RETURN The required statement keyword that sends execution back to the line after the corresponding GOSUB.
REM The main program flow
GOSUB SubroutineLabel
REM Execution continues here after RETURN is executed

HALT

REM --- Subroutine Definition ---
SubroutineLabel:
    REM Commands for the subroutine
    command1
    command2
    
RETURN

Rules

  • GOSUB saves the current location to an internal stack.
  • Every executed subroutine must terminate with RETURN to prevent errors and ensure proper program flow.
  • Subroutines are often placed at the end of the program, before the HALT statement, to prevent accidental execution.
  1. Stack Management: When GOSUB is executed, the return address is placed on an internal memory stack. RETURN then pops this address off the stack.
  2. Required Termination: Every time a subroutine is entered via GOSUB, it must terminate with a RETURN statement. Failure to do so will lead to stack inconsistency and program errors.
  3. Placement: Subroutines are often defined after the main program logic, typically before a HALT statement, to prevent the main program flow from accidentally falling into the subroutine without a GOSUB call.
  4. Nesting: Subroutines can call other subroutines (GOSUB within a subroutine). The internal stack manages these nested return addresses automatically.

Example

rem example program
print "A";
gosub bpoint
gosub cpoint
Halt

bpoint:
  print "B";
  return 

cpoint:
  print "C";
  gosub dpoint
  return

dpoint:
  print "D"
  return

output is: ABCD

Clone this wiki locally