Gosub

Syntax:

    Gosub label

Command Availability:

Available on all microcontrollers.

Explanation:

The Gosub command is used to jump to a label as a subroutine, in a similar way to Goto. The difference is that Return can then be used to return to the line of code after the Gosub.

Note:

Gosub should NOT be used if it can be avoided. It is not required to call a subroutine that has been defined using Sub — just write the name of the subroutine.

Example:

    'This program will flash an LED on portb bit 0 and play a beep on
    'porta bit 4, until the microcontroller is turned off.

    #chip 16F628A, 4 'Change this to suit your circuit

    #define SOUNDOUT PORTA.4
    #define LIGHT PORTB.0
    Dir LIGHT Out

    Do
    	'Flash Light
    	PulseOut LIGHT, 1 s
    	Wait 1 s
    	'Beep
    	Gosub PlayBeep          ' <<< the Gosub instruction
    Loop

    PlayBeep:
    Tone 200, 10
    Tone 100, 10
    Return

Key line: Gosub PlayBeep — jumps to the PlayBeep: label and, once Return is reached there, resumes execution on the line immediately after this Gosub call.

See Also:

  • Goto — an unconditional jump with no way back
  • Labels — defining the target a Gosub jumps to
  • Sub — the preferred, name-based alternative to Gosub