why not use DO WHILE in Fortran

Viewed 193

I'm studying Fortran from the book of Stephen Chapman "Fortran for Scientists and Engineers" (2018).

In page 134, the author wrote this:

Good Programming Practice:

Do not use DO WHILE loops in new programs. Use the more general while loop instead.

This sentence is puzzling me a lot. Is DO-WHILE an unwanted practice? I often find DO-WHILE neater to work with. Is there any disadvantage of using DO-WHILE in terms of speed?

DO-WHILE

INTEGER :: i = -1

DO WHILE (i < 0)
    PRINT *, 'Enter a non-negative number:'
    READ(*,*) i
END DO

General while loop:

INTEGER :: i = -1

DO
    PRINT *, 'Enter a non-negative number:'
    READ(*,*) i
    IF (i >= 0) EXIT
END DO
2 Answers

I can read from this book, just before the citation you give :

This construct is a special case of the more general while loop, in which the exit test must always occur at the top of the loop. There is no reason to ever use it, since the general while loop does the same job with more flexibility.

These are mostly facts, except "There is no reason to ever use it", which is just the personal opinion of the author. And anyway "there is no reason to use it" is not the same as "there are reasons to never use it" (as far as I know there are no such reasons).

That said, as a matter of style, in the particular example you give, the do while construct is not the best choice IMO, as it forces you to (artificially) initialize i before the loop. The initialization is not needed with the general do loop.

EDIT : as mentioned in the comments the initialization is actually still needed. But this is because of the READ(*,*) that does not garantee i to be assigned. Such a read should be protected against possible input errors, but this a different topic...

Is there any disadvantage of using DO-WHILE in terms of speed?

No. There is no general reason why do while would be slower than do. A decent optimising compiler should always be able to convert a do while loop into the equivalent do loop (although not always vice-versa). Of course, if you are interested in performance in a specific case then you should try both and profile the code rather than relying on generalities.

Is DO-WHILE an unwanted practice?

No. If a do while loop is the clearest way of expressing your code, use a do while loop.

The argument "X is more general than Y, so always use X instead of Y" is clearly a fallacious over-generalisation. A GOTO is more general than a do loop, but you certainly shouldn't be replacing your do loops with GOTOs.

Related