Go to the first, previous, next, last section, table of contents.


The CYCLE and EXIT Statements

The CYCLE and EXIT statements specify that the remaining statements in the current iteration of a particular active (enclosing) DO loop are to be skipped.

CYCLE specifies that these statements are skipped, but the END DO statement that marks the end of the DO loop be executed--that is, the next iteration, if any, is to be started. If the statement marking the end of the DO loop is not END DO---in other words, if the loop is not a block DO---the CYCLE statement does not execute that statement, but does start the next iteration (if any).

EXIT specifies that the loop specified by the DO construct is terminated.

The DO loop affected by CYCLE and EXIT is the innermost enclosing DO loop when the following forms are used:

CYCLE
EXIT

Otherwise, the following forms specify the construct name of the pertinent DO loop:

CYCLE construct-name
EXIT construct-name

CYCLE and EXIT can be viewed as glorified GO TO statements. However, they cannot be easily thought of as GO TO statements in obscure cases involving FORTRAN 77 loops. For example:

      DO 10 I = 1, 5
      DO 10 J = 1, 5
         IF (J .EQ. 5) EXIT
      DO 10 K = 1, 5
         IF (K .EQ. 3) CYCLE
10    PRINT *, 'I=', I, ' J=', J, ' K=', K
20    CONTINUE

In particular, neither the EXIT nor CYCLE statements above are equivalent to a GO TO statement to either label `10' or `20'.

To understand the effect of CYCLE and EXIT in the above fragment, it is helpful to first translate it to its equivalent using only block DO loops:

      DO I = 1, 5
         DO J = 1, 5
            IF (J .EQ. 5) EXIT
            DO K = 1, 5
               IF (K .EQ. 3) CYCLE
10             PRINT *, 'I=', I, ' J=', J, ' K=', K
            END DO
         END DO
      END DO
20    CONTINUE

Adding new labels allows translation of CYCLE and EXIT to GO TO so they may be more easily understood by programmers accustomed to FORTRAN coding:

      DO I = 1, 5
         DO J = 1, 5
            IF (J .EQ. 5) GOTO 18
            DO K = 1, 5
               IF (K .EQ. 3) GO TO 12
10             PRINT *, 'I=', I, ' J=', J, ' K=', K
12          END DO
         END DO
18    END DO
20    CONTINUE

Thus, the CYCLE statement in the innermost loop skips over the PRINT statement as it begins the next iteration of the loop, while the EXIT statement in the middle loop ends that loop but not the outermost loop.


Go to the first, previous, next, last section, table of contents.