Do loop skipping even number

谁说胖子不能爱 提交于 2019-12-10 23:16:37

问题


I represents the global variable i.e the name I represents same variable inside and outside the function. Fact is first called when I = 1, which is the first value written. This value is passed to the function's dummy argument N. The same I is now given the initial value 2 by the DO loop inside Fact, but since it is greater than N, the DO loop is not executed, so I still has the value 2 when Fact returns to be printed in the main program. However, I is now incremented to 3 in the DO loop in the main program, which is the value it has when the second call to Fact takes place.

PROGRAM Factorial 
IMPLICIT NONE 
INTEGER I

DO I = 1, 10 
PRINT*, I, Fact(I) 
END DO

 CONTAINS 
 FUNCTION Fact( N ) 
INTEGER Fact, N, Temp 
Temp = 1 
DO I = 2, N 
  Temp = I * Temp 
END DO 
Fact = Temp 
END FUNCTION 
 END

and Once it completes I goes from 2 to N where now N =3..Now the function must returns I =3 to main program such that next I should be 4 in Do loop of main program, but when compiled and run..it only shows factor for 3,5,7 and 9.....My question is why it skip 4 or 6 or 8.


回答1:


After exiting a loop the control variable gets the value of the upper bound + 1. However, it is illegal to modify the value of a loop control variable and anything can happen if you manage to do that despite the compiler's checks. It is an undefined behaviour then.


Not only that, you are aliasing the global I by using it as I as N at the same time inside the function. The compiler can probably perform various optimizations assuming that they are distinct when in fact they refer to the same variable. The program is therefore again illegal and unpredictable.

Consider this example and try to compile it with different optimization levels. You will get different answers:

i = 1
call s(i)

contains

  subroutine s(j)
    do k = 1, 10
      j = i + j
    end do
    print *, j
  end
end

Try it online!

This particular problem can probably be fixed by declaring i or the dummy argument target.



来源:https://stackoverflow.com/questions/56286986/do-loop-skipping-even-number

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