| Reorder Logical Expression
Tests |
The logical AND (&&) and logical OR (||)
operations are short-circuited in the C language. That is, the evaluation of each operand
is only done until the validity (true or false) of the expression is determined.
Therefore, the second operand of an AND operation will not be evaluated if the first
operand is false because the result is assured to be false. In the same manner, the second
operand of the OR operation is not evaluated if the first one is true since this assures
the result to be true. By taking advantage of this knowledge the programmer can order the
operands such that the first operand will most likely be true in an OR operation and false
in an AND operation. Also (as with repetitive computations) if a logical expression
appears multiple times within a function the code should be reworked to evaluate it once
and save the logical results in a temporary location. This can save time, especially with
large logical expressions. Additionally, the programmer should apply the Distributivity
Property to logical expression tests whenever possible. For example, assuming three
knowns; m, n, and p for equivalent logical expressions follow:
((n || m) && (n || p)) equals (n || (m && p))
((n && m) || (n && p)) equals (n && (m || p))
((n || m) || (n || p)) equals (n || (m || p))
((n && m) && (n && p)) equals (n && (m && p))
As is obvious, all of the equivalent expressions on the right of "equals"
requires one less expression evaluation than those on the left. |