next up previous contents index
Next: STOP Statement Up: Control Statements Previous: Guidelines

Computed GO TO Statement

  The computed GO TO statement is an alternative to the block-IF when a large number of options are required and they can be selected by the value of an integer expression. The general form of the statement is:
GO TO( label1, label2, ... labelN ), integer-expression
The comma after the right parenthesis is optional.

The expression is evaluated; if its value is one then control is transferred to the statement attached to the first label in the list; if it is two control goes to the second label, and so on. If the value of the expression is less than one or higher than N (where there are N labels in the list) then the statement has no effect and execution continues with the next statement in sequence. The same label may be present more than once in the list.

The computed GO TO suffers from many of the same drawbacks as the unconditional GO TO, since if its branches are used without restraint they can become impenetrable thickets. The best way is to follow the computed GO TO statement with the sections of code in order, all except the last terminated with its own unconditional GO TO to transfer control to the end of the whole structure.

Any computed GO TO structure could be replaced by an IF-block with a suitable number of ELSE IF clauses. If there are a very large number of cases then this would be a little less efficient; this has to be balanced against the increased clarity of the IF structure compared to the label-ridden GO TO.

An example of the use of the computed GO TO is given here in a subroutine which computes the number of days in a month, given the month number MONTH between 1 and 12, and the four-digit year number in YEAR. Note that each section of code except the last is terminated with a GO TO statement to escape from the structure.

 
      SUBROUTINE CALEND(YEAR, MONTH, DAYS) 
      INTEGER YEAR, MONTH, DAYS 
      GO TO(310,280,310,300,310,300,310,310,300,310,300,310)MONTH 
*           Jan Feb Mar Apr May Jun Jly Aug Sep Oct Nov Dec 
      STOP 'Impossible month number' 
*February: has 29 days in leap year, 28 otherwise. 
280   IF(MOD(YEAR,400) .EQ. 0  .OR. (MOD(YEAR,100) .NE. 0 
     $                          .AND. MOD(YEAR,4) .EQ. 0)) THEN 
          DAYS = 29 
      ELSE 
          DAYS = 28 
      END IF 
      GO TO 1000 
*   Short months 
300   DAYS = 30 
      GO TO 1000 
*   Long months 
310   DAYS = 31 
* return the value of DAYS 
1000  END


next up previous contents index
Next: STOP Statement Up: Control Statements Previous: Guidelines

Mario Storti
Wed Nov 4 19:32:56 ART 1998