Copyright 2008 Shoptalk Systems

GOSUB label


GOSUB causes execution to proceed to the program code following the label using the form 'GOSUB label'. The label can be either a traditional line number or a branch label name enclosed in square brackets, like this: [branchLabel].

After execution is transferred to the point of the branch label, then each statement will be executed in normal fashion until a RETURN is encountered. When this happens, execution is transferred back to the statement immediately after the GOSUB. The section of code between a GOSUB and its RETURN is known as a subroutine. One purpose of a subroutine is to save memory by having only one copy of code that is used many times throughout a program.


  print "Do you want to continue?"
  gosub [yesOrNo]
  if answer$ = "N" then [quit]
  print "Would you like to repeat the last sequence?"
  gosub [yesOrNo]
  if answer$ = "Y" then [repeat]
  goto [generateNew]

  input answer$
  answer$ = left$(answer$, 1)
  if answer$ = "y" then answer$ = "Y"
  if answer$ = "n" then answer$ = "N"
  if answer$ = "Y" or answer$ = "N" then return
  print "Please answer Y or N."
  goto [yesOrNo]

Using GOSUB [yesOrNo] in this case saves many lines of code in this example. The subroutine [yesOrNo] could easily be used many other times in such a hypothetical program, saving memory and reducing typing time and effort. This reduces errors and increases productivity.

Note: see also GOTO