Topic: DO LOOP not executing?

Getting back into Fortran after many years..................

The following DO LOOP does not show up as either an error or warning when editing the code:

implicit none

integer:: i = 0

do i = 0, -1
  write (*,*)'hello!'
end do

the program compiles just fine, and when you launch it, it runs but you never see "hello!".

My somewhat spotty memory is that one can do negative increments on DO loops, but the proper syntax would be something like

do i = 0, -10, -1

My first thought is perhaps the do loop is not executing because

do i = 0, -1, 1 is the same as do i = 0,0

however, using do i = 0,0 does execute the loop, and you see "hello!".

Now with that said, I am saving the program with .for extension, which I assume triggers the F66 & F77 compiler standards, but still seems weird.


Re: DO LOOP not executing?

You should think of the second number in the do loop as the inclusive point that will be the final loop step.  The problem with

do i = 0, -1

is that the variable i already falls outside the inclusive stopping point of -1, so the loop never executes.  In contrast, the line

do i = 0, 0

starts with a value of i that does fall within the inclusive upper limit of 0, and the inner code block executes.

I believe the Fortran 66 standard actually did guarantee that loops would execute at least once regardless of conditions, but that behavior is no longer the standard as of Fortran 77.

Jeff Armstrong
Approximatrix, LLC

Re: DO LOOP not executing?

For the fun of it, you could investigate do i = -0, -1

Zero is a funny critter. It can get you into trouble in programming and roulette.