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

匿名 (未验证) 提交于 2019-12-03 02:35:01

问题:

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?

回答1:

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.



回答2:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!