Search code examples
fortran

Can Fortran be forced to abide by the order of arguments in a logical operation?


I am looping through indices and I am checking if I am not in the first loop interation and another condition. I don't want the second condition to be evaluated if the first is .False..

do i = 1, n
    if ( i /= 1 .and. var(i) > var(i-1) ) then
        do something
    end if
end do

Clearly in this scenario, evaluating the second condition if the first condition is false will lead to an index error. Since if i = 0 then var(i-1) will be below the lower bounds.

Why is the second condition evaluated if the first is already .False.? Is there a way to avoid this without create a second if statement?


Solution

  • The shortest answer is 'no'. For the code shown, you have two option

    do i = 1, n
       if ( i /= 1 ) then
          if (var(i) > var(i-1) ) then
             do something
          end if
       end if
    end do
    

    or

    do i = 2, n
       if (var(i) > var(i-1) ) then
          do something
       end if
    end do