goto statement and its alternatives

In certain cases it may be convenient to perform an unconditional loop to another place in your code which is marked with a specific label. We already know that labels are represented by numbers written in column 2 to 5 of your Fortran code. The unconditional jump can then be requested by using a command goto followed by the label at which the program has to jump. Look at the following standard structure of using goto.

Example: Demonstration of an unconditional jump using the command goto.

      program MAIN
      integer a

      goto 11
 10   write(*,'("Here we go again")')

! lots of lines of your code

 11   write(*,'("Enter 1 to go around again:")')
      read(*,*) a
      if (a.eq.1) goto 10

      end

When started, this code displays Enter 1 to go around again: and waits for user input. After typing a number, this is assigned in a and the code checks whether a was 1. If so, it jumps to label 10, writes Here we go again and again asks for a number. On the other hand, if the number entered was not 1, the algorithm ends by reaching end.

Although you may encounter many older Fortran codes in which goto statements are frequently used, I recommend you to avoid using them whenever possible. As an alternative, you can always use a command exit which causes an immediate termination of the running loop and continuation your program after the corresponding enddo identifier. Another useful command is cycle which stops executing the current loop and goes back to the header of the loop to initiate a new cycle.

Example: Demonstration of using the commands exit and cycle.

      do n=1,1e4,100
         write(*,'("Executing cycle with n = ",I5)') n

         eval = (1+1.0/n)**n
         if (eval .ge. 2.718) exit

         write(*,'("  n = ", I5, ", e = ", F6.4)') 
     +        n,eval
      enddo

! here we are after calling exit

In the code above, the do-enddo loop is being executed until eval becomes greater or equal than $2.718$. Then, the loop is terminated by calling exit and the program continues after the enddo command. Now, substitute exit with cycle and think what happens. The correct answer is that whenever the calculated eval is greater or equal than $2.718$, the result n = ... is not displayed, but the loop keeps going until n reaches 10000. The initial message Executing cycle with n = ... is printed in each individual cycle.

Roman Gröger (2015-09-23)