Complete Versus Short Circuit Boolean Evaluation

The compiler supports two modes of evaluation for the and and or operators: complete evaluation and short-circuit (partial) evaluation. Complete evaluation means that each conjunct or disjunct is evaluated, even when the result of the entire expression is already determined. Short-circuit evaluation means strict left-to-right evaluation that stops as soon as the result of the entire expression is determined. For example, if the expression a and b is evaluated under short-circuit mode when a is False, the compiler won't evaluate b; it knows that the entire expression is False as soon as it evaluates a.

Short-circuit evaluation is usually preferable because it guarantees minimum execution time and, in most cases, minimum code size. Complete evaluation is sometimes convenient when one operand is a function with side effects that alter the execution of the program.

Short-circuit evaluation also allows the use of constructions that might otherwise result in illegal runtime operations. For example, the following code iterates through the string s, up to the first comma.

while (I <= Length(S)) and (S[I] <> ',') do begin


In the case where s has no commas, the last iteration increments I to a value which is greater than the length of s. When the while condition is next tested, complete evaluation results in an attempt to read S[I], which could cause a runtime error. Under short-circuit evaluation, in contrast, the second part of the while condition (S[I] <> ',') is not evaluated after the first part fails.

Use the $b compiler directive to control evaluation mode. The default state is {$B}, which enables short-circuit evaluation. To enable complete evaluation locally, add the {$b+} directive to your code. You can also switch to complete evaluation on a project-wide basis by selecting Complete Boolean Evaluation in the Compiler Options dialog (all source units will need to be recompiled).

Note: If either operand involves a Variant, the compiler always performs complete evaluation (even in the {$b} state).

Was this article helpful?

0 0
Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook

Post a comment