2

In the following do-loop, the index i runs from 1 to n - 1. If I print the value of i right after the loop exit, then I can confirm that gfortran prints the value of n (= 10 in the following case). Is this behavior always guaranteed according to the Fortran standard? (i.e., can we expect this behavior for all Fortran compilers/options?)

  program main
  implicit none
  integer :: i, n
  n = 10

  do i = 1, n - 1
     print *, "inside: ", i
  enddo

  print *, "after exit: ", i   !! guaranteed to be n?
  end
  • @francescalus According to the linked answers (and the standard docs), am I OK to understand that: if m1 = 1, m2 = n, m3 = 1 (the simplest setting), the "iteration count" starts from n (via 8.1.6.6.1.(3)) and varies as n, n-1, ..., 1, while do-variable varies as 1, 2, ..., n. Because the do-loop terminates when the iteration count is zero (according to 8.1.6.6.2 (1)), the corresponding do-variable becomes n+1 when the loop terminates (via 8.1.6.6.2.(3)). –  Jun 06 '20 at 10:30
  • 1
    Correct. The iteration counter takes n decrements to become zero, by which time the loop variable has also been incremented n times, to become n+1. As that detailed answer notes the loop variable is incremented _before_ the loop counter which has been decremented is tested against the value zero.# – francescalus Jun 06 '20 at 10:34

1 Answers1

1

Yes, the iteration variable is incremented at the end of every iteration, including the final one, and so you are guaranteed that i will have the value n after the loop completes in the example you provide

Ian Bush
  • 6,996
  • 1
  • 21
  • 27
  • Thanks! I recently found some code using this feature, and was afraid that this may be not portable. –  Jun 06 '20 at 10:34