6 Branching and Subroutines

Subroutines

The same sequence of statements may be executed often within a program. A subroutine allows the group of statements to occur only once and yet be accessed from different places in a program segment.

The GOSUB Statement

The GOSUB statement transfers control to a subroutine which begins at a specified statement.

GOSUB line id

A subroutine ends, logically, with RETURN which transfers control back to the statement immediately following the GOSUB statement.

The following example shows the use of GOSUB and RETURN:

10    X=5
20    Y=3
30    GOSUB Sub
40    X=X+Z
50    Y=Y/2
60    GOSUB Sub
70    Y=Y^3
80    X=0
90    GOTO Continue
100 Sub:! Print value of Z. *
110     Z=X+Y               *    Subroutine
120     PRINT Z             *
130     RETURN              *
 .
 .
200 Continue:!
 .
 .
Subroutines may be nested; this is, a second subroutine can be entered before the RETURN of the first is executed. For example:

1000  INPUT X,Y
1010  GOSUB Sub1
 .
 .
1090  STOP
1100  Sub1:!
1110    PRINT X,Y
1120    IF XY THEN GOSUB Sub2
 .
 .
1190    RETURN
1200  Sub2:!
1210    PRINT "XY"
 .
 .
1290    RETURN
The subroutine Sub2 is nested within subroutine Sub1.

Subroutines can be nested as deeply as available memory allows. When each RETURN is executed, control returns to the previously entered subroutine.

The ON GOSUB Statement

The ON GOSUB (computed GOSUB) statement accesses one of many subroutines, based on the value of a numeric expression.

ON numeric expression GOSUB line id list

The numeric expression is evaluated and rounded to an integer. A value of 1 causes the subroutine at the first line id in the list to be accessed, and so on. For example:

10   Main:        ! Setup report cycle.
20     INPUT "DO YOU WISH DAILY(1) OR WEEKLY(2) REPORTS?";Cycle
30     ON Cycle GOSUB Daily, Weekly
40     INPUT "SHOULD REPORTS BE DISPLAYED(1), PRINTED(2),OR OTHER(3)?";Output
50     ON Output GOSUB Display,Print,Other
 .
 .
110  STOP
120 Daily:            ! Setup daily schedule.
 .
 .
 .
160  RETURN
170 Weekly:           ! Setup weekly schedule.
 .
 .
 .
220  RETURN
230 Display: PRINTER IS 8
240  RETURN
250 Print: PRINTER IS 0
260  RETURN
270 Other:            ! Specify another output device.
 .
 .
 .
The main program begins with a series of prompts which the operator answers while setting up a report cycle. Each ON GOSUB branches the program to the appropriate subroutine--Daily, Weekly, Display, Print, or Other.

If the value of the numeric expression is less than one or greater than the number of line ids in the list, ERROR 19 occurs.


Eloquence Language Manual - 19 DEC 2002