Optimising logical expressions
Brooks Moses
brooks.moses@codesourcery.com
Wed Jun 20 21:39:00 GMT 2007
Terry Frankcombe wrote:
> With gfortran/gcc, is there a significant difference in the code the
> optimiser produces from:
>
> if (A.and.B) ...
>
> and
>
> if (A) then
> if (B) ...
> endif
>
> ?
Yes, there is a difference -- note that A and B can both be expressions
which have side effects. Although some people's interpretations of the
standard would say that a compiler is not strictly required to always
produce the side effects from A and B when evaluating A.and.B, most
compilers do produce them, and a lot of code relies on the assumption
that both sets of side effects will always be produced. Thus, GFortran
always produces the side effects from both.
Furthermore, even if the compiler were to short-circuit things, there's
no guarantee that it wouldn't do "if (B) then if (A)...".
Now, it may happen that, when B obviously doesn't produce side effects,
the code that GFortran produces today may short-circuit it; I'm not
sure. However, even if it does, there is certainly no guarantee that it
will still do that in the future. :)
> (No, I'm not trying to avoid an invalid B. I'm curious about the case
> where B is expensive.)
In that case, you should explicitly specify what you want. Unlike in C,
the .and. operator is not required by the standard to short-circuit its
second operand if the first is true, and so it you shouldn't use it when
that's what you want. :)
- Brooks
More information about the Fortran
mailing list