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?
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.
Advertisements. The do loop construct enables a statement, or a series of statements, to be carried out iteratively, while a given condition is true.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With