EXIT and CYCLE
Two statements change the flow of a running loop without changing its header. exit leaves the construct, cycle skips the rest of the current iteration, and both take the name of a loop when the loop they mean is not the innermost one. This lesson covers the search that stops at the first hit, the filter that skips part of the data, and the error a program gets when it leaves a loop that is not there.
EXIT
exit ends the innermost loop immediately and execution continues after its end do. It is the Fortran word for what other languages call break, and it takes no condition: the condition is the if around it.
The file search.f90:
program search
implicit none
integer, parameter :: n = 6
integer :: values(n), i, found
values = [4, 8, 15, 16, 23, 42]
found = 0
do i = 1, n
if (values(i) == 15) then
found = i
exit
end if
end do
print *, "found at:", found
print *, "i :", i
end program search
gfortran -Wall -Wextra -std=f2018 search.f90 -o search
./search
found at: 3
i : 3
The loop stops at the third element instead of walking the remaining three. The counter is 3 after the loop, a value the standard leaves undefined but every compiler produces; a program that needs the position uses found, which the loop set before leaving.
A search with a sentinel is the same loop without the if in it, and it is a legitimate optimisation in a hot loop. It is harder to read, and the version above is what a reader should meet first.
CYCLE
cycle skips the rest of the body and goes to the next iteration, which is the continue of other languages. It is the readable form of a filter: the body states the condition for skipping, and the work below it applies to the values that survive.
The file skip.f90:
program skip
implicit none
integer :: i, total
total = 0
do i = 1, 10
if (mod(i, 2) == 0) cycle
total = total + i
end do
print *, "sum of odds:", total
end program skip
gfortran -Wall -Wextra -std=f2018 skip.f90 -o skip
./skip
sum of odds: 25
The one-line if with cycle is one of the few places where the short form beats the block: the condition and its consequence are one idea, and the block would add four lines of indentation around a single statement.
A named EXIT
In two nested loops, a plain exit leaves the inner one and the outer loop continues. When the work is finished and both loops must end, the outer loop carries a name and the exit names it.
The file nested_exit.f90:
program nested_exit
implicit none
integer :: i, j, count
count = 0
outer: do i = 1, 3
inner: do j = 1, 3
if (i * j > 4) exit outer
count = count + 1
end do inner
end do outer
print *, "pairs visited:", count
print *, "last i, j :", i, j
end program nested_exit
gfortran -Wall -Wextra -std=f2018 nested_exit.f90 -o nested_exit
./nested_exit
pairs visited: 5
last i, j : 2 3
Five pairs were counted, and the sixth, i = 2, j = 3, hit the condition and left both loops. cycle outer works the same way and skips to the next value of the outer variable, which is how a program skips a whole row of a matrix when one of its columns fails.
Without the name the exit would leave only the inner loop, and the program would continue with i = 3: a different answer that a reader cannot see from the output. That is why a named exit is worth the extra word even when a plain one would compile.
A search that stops
The combination that appears in real code most often is a search inside a loop with an early exit, and the question a reader asks first is what the variables hold when nothing was found. Two habits answer it without a comment:
- Initialise the result before the loop to a value that cannot be a hit, as the search above does with found = 0.
- Test the result after the loop rather than the loop variable, because the loop variable is undefined after a normal exit.
The intrinsics findloc and any do the same job for an array without a loop at all, and the lesson on MAXLOC, MINLOC and FINDLOC shows them. The loop above is what those intrinsics compile to.
EXIT outside a loop
exit belongs to a construct, so a program that uses it where no loop is open does not build. The message names the statement and the rule.
The file outside.f90:
program outside
implicit none
integer :: i
i = 1
exit
print *, i
end program outside
gfortran -Wall -Wextra -std=f2018 outside.f90 -o outside
outside.f90:5:6:
5 | exit
| 1
Error: EXIT statement at (1) is not within a construct
A program that must stop in the middle of the main body uses stop, which ends the whole program, or error stop, which ends it with a failure status. The lesson on STOP is about the difference.
Exercises
- Search the array for 99 instead of 15. What does the program print, and why is that the right answer?
- Replace cycle with exit in the second program. What does the sum become?
- Change exit outer to exit in the third program. How many pairs are visited now?
- Write a loop that skips every value divisible by three and sums the rest from 1 to 20.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does EXIT do?
Answer
It leaves the innermost loop or the named construct
EXIT ends the construct; STOP is what ends the program.
-
What does CYCLE do?
Answer
It skips the rest of the body and starts the next iteration
CYCLE is the continue of other languages: the next iteration begins.
-
What does
exit outerleave?Answer
The loop named outer, whatever its nesting depth
The name selects the construct, not the innermost one.
-
Where may EXIT appear?
Answer
Inside a DO construct, possibly named by it
Outside a construct the compiler reports that the statement is not within one.
-
What does this program print?
program p implicit none integer :: i, s s = 0 do i = 1, 10 if (i > 3) exit s = s + i end do print *, s end program pAnswer
6
The loop adds 1, 2 and 3 and leaves before adding 4.
-
What is the loop variable after an EXIT?
Answer
Whatever it held when the EXIT ran, which the standard leaves undefined
The standard does not define it, so a program uses the variable it set itself.
-
Why initialise the result before a search loop?
Answer
So the not-found case has a defined value after the loop
A sentinel value answers the not-found case without reading the loop variable.
-
Which combination is the readable form of a filter?
Answer
A one-line IF with CYCLE at the top of the body
The condition and its consequence are one line, and the work below applies to survivors.
-
What error does
exitoutside a loop give?Answer
Error: EXIT statement at (1) is not within a construct
The statement belongs to a construct and the compiler says there is none.
-
Which intrinsic finds the position of a value without a loop?
Answer
findloc
findloc returns the first matching position of an array.
The programs on this page were built with GNU Fortran (Alpine 15.2.0) 15.2.0 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev