表5.2 列出了关系与逻辑操作符的五种优先级,值得牢记。
The relational and logical operators take operands of arithmetic or pointer type and return values of type bool.
Logical AND and OR Operators
The logical operators treat their operands as conditions (Section 1.4.1, p. 12). The operand is eva luated; if the result is zero the condition is false, otherwise it is true. The overall result of the AND operator is true if and only if both its operands eva luate to true. The logical OR (||) operator eva luates to true if either of its operands eva luates to true. Given the forms
- expr1 && expr2
- expr1 || expr2
expr2 is eva luated if and only if expr1 does not by itself determine the result. In other words, we’re guaranteed that expr2 will be eva luated if and only if
· In a logical AND expression, expr1 eva luates to true. If expr1 is false, then the expression will be false regardless of the value of expr2. When expr1 is true, it is possible for the expression to be true if expr2 is also true.
· In a logical OR expression, expr1 eva luates to false; if expr1 is false, then the expression depends on whether expr2 is true.
The logical AND and OR operators always eva luate their left operand before the right. The right operand is eva luated only if the left operand does not determine the result. This eva luation strategy is often referred to as “short-circuit eva luation.”
A valuable use of the logical AND operator is to have expr1 eva luate to false in the presence of a boundary condition thatwould make the eva luation of expr2 dangerous. As an example, we might have a string that contains the characters in a
sentence and we might want to make the first word in the sentence all uppercase.
We could do so as follows:
- string s("Expressions in C++(www.cppentry.com) are composed...");
- string::iterator it = s.begin();
-
- while (it != s.end() && !isspace(*it)) {
- *it = toupper(*it);
- ++it;
- }
In this case, we combine our two tests in the condition in the while. First we test whether it has reached the end of the string. If not, it refers to a character in s. Only if that test succeeds is the right-hand operand eva luated. We’re guaranteed that it refers to an actual character before we test to see whether the character is a space or not. The loop ends either when a space is encountered or, if there are no spaces in s, when we reach the end of s.