Expressions - order of evaluation
Original Reporter info from Mantis: zoran
-
Reporter name: Zoran Vučenović
Original Reporter info from Mantis: zoran
- Reporter name: Zoran Vučenović
Description:
Take a look at these two quotes from Refernce manual:
Quote 1 (Under Boolean operators -- https://www.freepascal.org/docs-html/current/ref/refsu47.html):
Remark: By default, boolean expressions are evaluated with short-circuit evaluation. This means that from the moment the result of the complete expression is known, evaluation is stopped and the result is returned. For instance, in the following expression:
B := True or MaybeTrue;
The compiler will never look at the value of MaybeTrue, since it is obvious that the expression will always be True. As a result of this strategy, if MaybeTrue is a function, it will not get called ! (This can have surprising effects when used in conjunction with properties)
Quote 2 (chapter Expressions, when talking about operator precedence -- https://www.freepascal.org/docs-html/current/ref/refch12.html):
Remark: The order in which expressions of the same precedence are evaluated is not guaranteed to be left-to-right. In general, no assumptions on which expression is evaluated first should be made in such a case.
... etc.
So, according to Qoute 2, in the example from Quote 1, compiler can choose to first evaluate the right side of OR operator. Then, we cannot rely on short-circuit evaluation.
I need to say that I often use something like "if (Obj <> nil) and Obj.SomeMethod do..." and after many years of programming with FPC, and using short-circuit evaluation all the time, I never encountered any bad surprises.
Therefore, I think that it actually always evaluates left side first, at least when short-circuit evaluation is switched on.
The documentation should clear this. I think that it should be mentioned clearly in both remarks I quoted:
- in boolean operators, that boolean operators are excluded from general rule, at least when short-circuit evaluation is enabled, and the order left to right is guaranteed in this case.
- in Expressions, it should be added to quoted remark, that this remark doesn't include boolean operators (at least when short-circuit evaluation is enabled) and that these are guaranteed to be evaluated from left to right.
Mantis conversion info:
- Mantis ID: 35661
- Fixed in version: 3.3.1
- Fixed in revision: 1621 (#ff6ee937).
- Target version: 3.2.0