|
|
|
|
|
|
|
Caution: It's easy to confuse the logical operators && and || with two other C++ operators, & and |. We don't discuss the & and | operators here, but we'll tell you that they are used for manipulating individual bits within a memory cella role quite different from that of the logical operators. If you accidentally use & instead of &&, or | instead of ||, you won't get an error message from the compiler. But your program probably will compute wrong answers. Some programmers pronounce && as and-and and || as or-or to avoid making mistakes. |
|
|
|
|
|
|
|
|
Consider the logical expression |
|
|
|
|
|
|
|
|
Some programming languages use full evaluation of logical expressions. With full evaluation, the computer first evaluates both subexpressions (both i == 1 and j > 2) before applying the && operator to produce the final result. |
|
|
|
|
|
|
|
|
In contrast, C++ uses short-circuit (or conditional) evaluation of logical expressions. Evaluation proceeds from left to right, and the computer stops evaluating subexpressions as soon as possiblethat is, as soon as it knows the truth value of the entire expression. How can the computer know if a lengthy logical expression is TRUE or FALSE if it doesn't examine all the subexpressions? Let's look first at the AND operation. |
|
|
|
|
|
|
|
|
An AND operation yields the value TRUE only if both of its operands are TRUE. In the expression above, suppose that the value of i happens to be 95. The first subexpression is FALSE, so it isn't necessary even to look at the second subexpression. The computer stops evaluation and produces the final result of FALSE. |
|
|
|
 |
|
 |
|
|
Short-Circuit (Conditional) Evaluation Evaluation of a logical expression in left-to-right order with evaluation stopping as soon as the final truth value can be determined. |
|
|
|
|
|
|
|
|
With the OR operation, the left-to-right evaluation stops as soon as a TRUE subexpression is found. Remember that an OR produces a result of TRUE if either one or both of its operands are TRUE. Given this expression: |
|
|
|
|
|
|
|
|
if the first subexpression is TRUE, evaluation stops and the entire result is TRUE. The computer doesn't waste time with an unnecessary evaluation of the second subexpression. |
|
|
|
|
|