EXIT

Purpose

The EXIT statement terminates execution of a DO construct or DO WHILE construct before the construct terminates all of its iterations. Fortran 2008 beginsIn addition, it can be used to terminate execution of a specified construct that is not DO or DO WHILE.Fortran 2008 ends

Syntax

Read syntax diagramSkip visual syntax diagram
>>-EXIT--+----------------+------------------------------------><
         '-construct_name-'   

construct_name
The name of a construct.
Fortran 2008 begins
It can be one of the following constructs:
  • ASSOCIATE
  • BLOCK
  • DO
  • IF
  • SELECT CASE
  • SELECT TYPE
Fortran 2008 ends

Rules

If construct_name is specified, the EXIT statement must be within the construct specified by construct_name. If construct_name is not specified, the EXIT statement must be within the range of at least one DO or DO WHILE construct.

If construct_name is specified, the EXIT statement belongs to the construct specified by construct_name. If construct_name is not specified, the EXIT statement belongs to the DO or DO WHILE construct that immediately surrounds it.

If an EXIT statement belongs to a DO or DO WHILE construct, execution of the EXIT statement causes the construct to become inactive. If the EXIT statement is nested in any other DO or DO WHILE constructs, they also become inactive. Any DO variable present retains its last defined value. If the DO construct has no construct control, it will iterate infinitely unless it becomes inactive. The EXIT statement can be used to make the construct inactive.

Fortran 2008 beginsIf an EXIT statement belongs to a construct that is not DO or DO WHILE, execution of the EXIT statement terminates execution of the construct. Any DO or DO WHILE loops contained within the construct become inactive.Fortran 2008 ends

An EXIT statement can have a statement label; it cannot be used as the labeled statement that terminates a construct.

Examples

Example 1: The following example illustrates the usage of the EXIT statement in the DO and DO WHILE statements:
      LOOP1: DO I = 1, 20
         N = N + 1
10       IF (N > NMAX) EXIT LOOP1           ! EXIT from LOOP1

         LOOP2: DO WHILE (K==1)
            KMAX = KMAX - 1
20          IF (K > KMAX) EXIT              ! EXIT from LOOP2
         END DO LOOP2

         LOOP3:  DO J = 1, 10
             N = N + 1
30           IF (N > NMAX) EXIT LOOP1       ! EXIT from LOOP1
             EXIT LOOP3                     ! EXIT from LOOP3
         END DO LOOP3

      END DO LOOP1
Fortran 2008 begins
Example 2: The following example shows how the EXIT statement is used to terminate execution of a BLOCK construct:
a : BLOCK
  DO i = 1, num_in_set
    IF (X == a(i)) EXIT a       ! EXIT from the a BLOCK construct
  END DO
  CALL r
END BLOCK a 
Fortran 2008 ends

Related information