Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.

logical and behaviour

David_Mccabe
Beginner
515 Views

Hi.

The output from the following program is:

test1 invoked

test2 invoked

[fortran]

program IfAnd

    if (test1().and.test2()) then

        ! do nothing

    endif

    write(*,"(A)") "hit return..."

    read(*,*)

contains

    function test1()

    logical test1

        test1 = .false.

        write(*,"(A)") "test1 invoked"

    end function test1

    function test2()

    logical test2

        test2 = .false.

        write(*,"(A)") "test2 invoked"

    end function test2

end program IfAnd

[/fortran]

I was expecting only one procedure to be evaluated as the second evaluation is unnessesary.

Q. Is there some compiler switch to change this behaviour?

 

Thanks

 

0 Kudos
3 Replies
TimP
Honored Contributor III
515 Views
You would need to be explicit if you want a specified order of evaluation and short-cutting: if(test1())then if(test2()then ! do something endif endif The way you have written it, without the writes you would have no guarantee whether none, one, or both functions will execute. The presence of side effects (writes) and absence of a specified evaluation order results in both being evaluated, but it looks like you are taking some chances of unexpected behavior. If you are following a C analogy, what you wrote carries some of the flavor of inline int test1(int),test2(int); if(test1() & test2()); // note the single & which doesn't support short-cutting
0 Kudos
David_Mccabe
Beginner
515 Views
I see, so the evaluation order is determined by the compiler. Procedures with side effects are always evaluated. Procedures without side effects may then be bypassed. Thanks for the prompt reply
0 Kudos
Steven_L_Intel1
Employee
515 Views
It's not that simple. The Fortran language allows the compiler to evaluate any logically equivalent expression, to any degree of completeness and in any order, it finds appropriate. You cannot guarantee which of these functions will be called. Use a nested IF-THEN to force an order.
0 Kudos
Reply