Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

loops

fortran

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?

like image 863
carla Avatar asked Mar 26 '12 22:03

carla


People also ask

Do loops index?

This DO Index loop uses a index variable for its start and end value. The SAS statements are repeatedly executed until the final value of the index variable is reached.

What is DO loop in Fortran?

Advertisements. The do loop construct enables a statement, or a series of statements, to be carried out iteratively, while a given condition is true.


2 Answers

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.

like image 30
Tony Hopkinson Avatar answered Nov 25 '22 22:11

Tony Hopkinson


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

like image 63
GummiV Avatar answered Nov 25 '22 20:11

GummiV