Value of index variable after loop exit in Fortran

Viewed 183

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
1 Answers

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

Related