[fpc-pascal] Boolean expression short-circuit
Michalis Kamburelis
michalis at camelot.homedns.org
Tue Nov 22 15:57:55 CET 2005
Kornel Kisielewicz wrote:
> Ok, I've been arguing over that with a friend of mine for a couple of
> e-mail's now... I need your help!
>
> Let me show an example first:
>
> type TFoo = class end;
> var Foo : TFoo;
>
> The question is, wether this is valid:
>
> if (Foo <> nil) and (Foo.inheritsFrom(TFoo)) then do_something;
>
> I would have no questions about that (first the Foo is checked, so
> inheritsFrom is called ONLY if Foo <> nil) if it weren't for the
> statement in the manual:
>
> <quote>
> Remark: The order in which expressions of the same precedence are
> evaluated is not guaranteed to be leftto-right. In general, no
> assumptions on which expression is evaluated first should be made in
> such a case. The compiler will decide which expression to evaluate first
> based on optimization rules.
> </quote>
>
This concerns +, -, * and such operators. Compiler can rearrange your
arithmetical statements to make them optimized. Both Delphi and FPC.
This *doesn't* concern boolean operators, like "and", "or" -- these are
guaranteed to be calculated left-to-right. That's because we like them
to be predictable, just like your example "if (Foo <> nil) and (Foo..."
demonstrates.
> Can I make the assumption that boolean expressions are GUARANTEED to be
> evaluated left-to-right?
>
Yes.
Michalis
More information about the fpc-pascal
mailing list