carla
carla

Reputation: 2251

Why is the Fortran DO loop index larger than the upper bound after the loop?

I am looking inside the code of an air quality model written in fortran, and have some questions regarding the way fortran passes variables out from do-loops.

This very simple example illustrates what I mean:

   PROGRAM carla
   IMPLICIT NONE
   !
   INTEGER, PARAMETER :: LM = 24, DEZASSEIS = 16
   INTEGER            :: L, VARIAVEL, SOMA
   !
   DO L=1,LM
   WRITE(*,*) 'L = ', L
   END DO
   !
   WRITE(*,*) 'I am now ouside of the DO loop.'
   WRITE(*,*) 'I would expect L=LM=24... And SOMA=40'
   WRITE(*,*) 'L = ', L
   SOMA = DEZASSEIS + L
   WRITE(*,*) 'SOMA = ', SOMA
   END PROGRAM carla

I would expect L=LM=24... And SOMA=40... But instead I get:

   L =           25
   SOMA =           41

I don't understand why once we are outside of the DO loop, L does not keep the last value assumed (SOMA would be thus equal to 40), and keep increasing...

Can somebody give me a hint?

Upvotes: 5

Views: 1142

Answers (2)

GummiV
GummiV

Reputation: 236

Fortran doesn't work that way. ( it's not Matlab :P )

Exercise caution if using the index variable outside the DO loop because the variable is incremented at the end of the loop, i.e., it will be stepsize more than the final value.

http://www.oc.nps.edu/~bird/oc3030_online/fortran/do/do.html

Which explains why L=25 after the loop.

Edit: The following is incorrect. See M.S.B.'s comment below

In Fortran the DO-variable ... should never be referenced outside the loop without first explicitly assigning a value to it. - http://www.esm.psu.edu/~ajm138/fortranexamples.html

Upvotes: 4

Tony Hopkinson
Tony Hopkinson

Reputation: 20320

Loop from 1 to 24, So when it gets to 25, loop has finished.

Think of it as 
(pseudocode)
LL = 1
While LL < 25
 LL = LL + 1;

As GummiV stated, don't do this. Loops are prime targets for compiler optimisations, no guarantee what's in there after the loop has executed. Could have just as easily been 0, one optimisation reverses the count because detecting LL = 0 is quicker than LL > 24 on some machines. Not much quicker, but compiler guys have a real problem with it'll do.

Upvotes: 1

Related Questions