j3-fortran / fortran_proposals

Proposals for the Fortran Standard Committee
178 stars 15 forks source link

"do / else" proposal #342

Open certik opened 1 week ago

certik commented 1 week ago

https://fortran-lang.discourse.group/t/for-else-or-do-else-in-fortran/8696

Example:

condition = .false.
do i = 1, 10
    .......
    if (condition) exit
else
    ! This block only executes if the do loop doesn't exit.
    error stop "Condition not met"
enddo

which would be equivalent to:

condition = .false.
do i = 1, 10
    ......
    if (condition) exit
enddo
if (.not. condition) error stop "Condition not met"

Similar to Python's "for else": https://docs.python.org/3/tutorial/controlflow.html#else-clauses-on-loops

everythingfunctional commented 1 week ago

Just to be clear, the above is equivalent to the below?

condition = .false.
do i = 1, 10
    ...
    if (condition) exit
end do
if (i > 10) then
    ! This block only executes if the do loop doesn't exit.
    error stop "Condition not met"
end if
certik commented 1 week ago

Yes. I updated the above description with an example. (I don't like using loop variables after the loop, but that's a separate issue: is it even specified by the standard?)

everythingfunctional commented 1 week ago

is it even specified by the standard?

Yes, although it's not immediately obvious. From 11.1.7.4.3 The execution cycle

The DO variable, if any, is incremented by the value of the incrementation parameter m3

and from 11.1.7.4.5 Loop termination

When a DO construct becomes inactive, the DO variable, if any, of the DO construct retains its last defined value.

So if a do loop completes all its iteration, the standard says it has a value > the ending value.

certik commented 1 week ago

@everythingfunctional thanks for the clarification!

klausler commented 1 week ago

Looks like syntactic vinegar for the existing and less mysterious

search: block
  do j = 1, 10
    ...
    if (condition) exit search
  end do
  error stop 'nope'
end block