while-loopfortrando-whiledo-loops

why not use DO WHILE in Fortran


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

Solution

  • 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.