Why does the second if-clause even execute?

前端 未结 2 1034
无人共我
无人共我 2021-01-24 11:23

I have a do while loop in my program, who\'s condition to continue keeps giving me off-by-one errors and I can\'t figure out why. It looks like this:



        
相关标签:
2条回答
  • 2021-01-24 11:58

    Extending the answer High Performance Mark, here is one way to rewrite the loop:

    ii_loop: do
    
      if (ii .gt. nri) exit ii_loop
      if (ed(ii) .gt. e1) exit ii_loop
    
      ! do some stuff
    
      ii = ii + 1
    
    end do ii_loop
    
    0 讨论(0)
  • 2021-01-24 12:04

    In contrast to some languages Fortran does not guarantee any particular order of evaluation of compound logical expressions. In the case of your code, at the last go round the while loop the value of ii is set to nri+1. It is legitimate for your compiler to have generated code which tests ed(nri+1)<=e1 and thereby refer to an element outside the bounds of ed. This may well be the cause of your program's crash.

    Your expectations are contrary to the Fortran standards prescriptions for the language.

    If you haven't already done so, try recompiling your code with array-bounds checking switched on and see what happens.

    As to why your test didn't smoke out this issue, well I suspect that all your test really shows is that your compiler generates a different order of execution for different species of condition and that you are not really comparing like-for-like.

    0 讨论(0)
提交回复
热议问题