Chapter 4 – Procedures and Subroutines

Branching

As we already saw, in the course of a program we may need to jump somewhere else inside the program. So far we've seen the GO TO keyword that does just that. GO TO however has disadvantages: If the code jumped to by GO TO needs to be used by some other portion of the program and then return to where it was called, you would need to either introduce complex code to find where the jump came from as to use an appropriate GO TO command to return to it or copy the code multiple times to be called individually by each location.

GO SUB and RETURN

To account for this deficiency, NextBASIC has the statements GO SUB (GO to SUBroutine) and RETURN which are used together. Reusable code called upon multiple times within a program is known as a subroutine, and it can be used – or called – from anywhere else in the program without having to type it again or remember where the call came from. The call to a subroutine takes the form:

GO SUB n

where n is the line number or label of the first line in the subroutine. It is just like GO TO n except that the computer remembers where the GO SUB statement was so that it can come back again after doing the subroutine. It does this by putting the line number and the statement number within the line (together these constitute the return address) on top of a pile of them (the NextBASIC return stack – see Chapter 23 for details):

The command

RETURN

takes the top return address off the GO SUB stack, and goes to the statement after it. As an example, let's look at the number guessing program again. Retype it as follows:

 10 REM A rearranged guessing
    game
 20 INPUT a: CLS
 30 INPUT "Guess the number ",b
 40 IF a=b THEN PRINT
    "Correct": STOP
 50 IF a<b THEN GO SUB 100
 60 IF a>b THEN GO SUB 100
 70 GO TO 30
100  PRINT "Try again"
110 RETURN

The GO TO statement in line 70 is very important because otherwise the program will run on into the subroutine and cause an error (7 RETURN without GO SUB) when the RETURN statement is reached.

Here is another rather silly program illustrating the use of GO SUB:

100 x=10
110 GO SUB 500
120 PRINT s
130 x+=4

ZX Spectrum Next User Manual, 3rd Edition (ISBN 978-1-5272-5496-1), written and illustrated by Phoebus R. Dokos. Copyright © 2020-2024 Phoebus Dokos / SpecNext Ltd. Licensed under CC BY-NC-SA 4.0. This is a transcription and can contain errors; check any doubt against the printed page.