Welcome to AE Resources
Converted document Converted document

FORTRAN 90+: GOTO

The GOTO command used to be a very common statement in Fortran 77, but most of its functions are possible through DO and IF statements, and common usage of GOTO is not recommended in modern Fortran programing. It is important to understand the GOTO command in case it is encountered when handling old programs, and in the rare cases where it can be useful. GOTO statement is very easy to implement. The basic format is
GOTO number !The number can be any integer
The integer is placed at the beginning of the line of code that the program will jump to. The programmer is cautioned that the line will not be skipped in the course of program execution. Take, for example, the following simple illustration
PROGRAM goto
     IMPLICIT NONE
     INTEGER :: a
          READ(*,*) a
          IF (a == 9) THEN
               GOTO 10
          ELSE
               GOTO 11
          END IF
          10 WRITE(*,*) "It was 9"
          11 WRITE(*,*) "It was not 9"
          WRITE(*,*) "Some other code here"
 END PROGRAM goto
If ’9’ was input, the result would be the following statement written to the terminal.
It was 9
It was not 9
Some other code here
This is most likely not what the programmer intended since the output contradicts itself. The lines labeled 10 and 11 need to be isolated from one another (as they would be within the block statement). Notice that if a number other than 9 were input, the program behaves as the programmer intended:
It was not 9
Some other code here
The code has jumped to the line labeled 11 and continued to execute.
GOTO is not recommended except in situations where some other intrinsic statement absolutely will not work (rare!). Its main usage is now during debugging where the programmer may wish to skip programmed code or add in new code to help understand why the program is not functioning properly. Suppose in subroutine fraction, the computed variable f was giving errors. This would happen in a fraction if the denominator is 0.0. The programmer can add new debugging statements to skip the computation of the fraction and determine why the denominator is 0.0:
SUBROUTINE fraction (a,b,c, f)
     ........
     REAL ::  f, x, y, a, b, c
     x  = a
     y = b * c
     IF( y == 0.0) GOTO 998  !New line to help debug code
     f = x/y
     ! New debugging code added below here
     GO TO 999
     998 CONTINUE
     WRITE(*,*) ’ y is 0.0!’
     WRITE(*,*) ’ b, c = ’, b,c
     999 CONTINUE
     ! New debugging code ends here
END SUBROUTINE fraction
If the denominator is 0, then the code execution moves to 998, where debugging statements are written. If the denominator is not zero, then the fraction is computed successfully, and the code execution skips to line 999 and exits the subroutine. Notice that here a block IF statement can be used as (or one could argue, more) successfully.