Chapter 2 C and C++ Source-Level Optimizations 17
Software Optimization Guide for AMD64 Processors
25112 Rev. 3.06 September 2005
2.6 Arrange Boolean Operands for Quick Expression
Evaluation
Optimization
In expressions that use the logical AND (&&) or logical OR (||) operator, arrange the operands for
quick evaluation of the expression:
Application
This optimization applies to:
• 32-bit software
• 64-bit software
Rationale
C and C++ compilers guarantee short-circuit evaluation of the boolean operators && and ||. In an
expression that uses &&, the first operand to evaluate to false terminates the evaluation; subsequent
operands are not evaluated. In an expression that uses ||, the first operand to evaluate to true terminates
the evaluation.
When used to control program flow, expressions involving && and || are translated into a series of
conditional branches. This optimization minimizes the total number of conditions evaluated and
branches executed.
Example 1
In the following code, the operands of && are not arranged for quick expression evaluation because the
first operand is not the condition case most likely to be false (it is far less likely for an animal name to
begin with a ‘y’ than for it to have fewer than four characters):
char animalname[30];
char *p;
p = animalname;
if ((strlen(p) > 4) && (*p == 'y')) { ... }
If the expression uses this
operator
Then arrange the operands from left to right in decreasing
probablity of being
&& (logical AND) False
|| (logical OR) True