fortrangfortran

Fortran 77 DO label also used by IF/GOTO


I have an old fortran 77 code, which I like to keep unchanged as much as possible. Since gfortran gives the loop warnings, I was thinking of changing the non-block loops to block mode. But then I realised that some GOTO statements use the same loop labels as well. Now I am not sure how the compiler behaves with regard to the statements that follow the labels.

So my question is whether I can "modernise" this example code:

      INTEGER i
      DO 30 i = 1, 14
      IF <SOME CONDITION> GOTO 30
      <SOME COMMANDS HERE>
  30  WRITE(*,*) i
      <SOME FOLLOWING STATEMENTS>

To this one:

      INTEGER i
      DO 30 i = 1, 14
      WRITE(*,*) i
      IF <SOME CONDITION> GOTO 30    
      <SOME COMMANDS HERE>  
  30  CONTINUE  
      <SOME FOLLOWING STATEMENTS>

Or even this one:

      INTEGER i
      DO i = 1, 14
      WRITE(*,*) i
      IF <SOME CONDITION> GOTO 30    
      <SOME COMMANDS HERE>  
      END DO
  30  <SOME FOLLOWING STATEMENTS>

In this latter form, I am not sure whether the label should go to the END DO or to the following statement?


Solution

  • The line with the loop termination label belongs to the loop (i.e. the instruction is executed at each iteration), meaning that in your initial version the loop is always executed until i=15. Consequently, your 3rd version is wrong. The second version is OK.

    But if you want to modernize the code, you may write instead:

          INTEGER i
          DO i = 1, 14
             IF (.NOT.<SOME CONDITION>) THEN    
                <SOME COMMANDS HERE>
             END IF
             WRITE(*,*) i
          END DO  
          <SOME FOLLOWING STATEMENTS>
    

    or alternatively

          INTEGER i
          DO i = 1, 14
             WRITE(*,*) i
             IF (<SOME CONDITION>) CYCLE ! directly starts the next iteration
             <SOME COMMANDS HERE>
          END DO  
          <SOME FOLLOWING STATEMENTS>