Logical NOT Operator
The logical NOT operator (!) treats its operand as a condition. It yields a result that has the opposite truth value from its operand. If the operand eva luates as nonzero, then ! returns false. For example, we might determine that a vector has elements by applying the logical NOT operator to the value returned by empty:
-
- int x = 0;
if (!vec.empty()) x = *vec.begin();
The subexpression
- !vec.empty()
eva luates to true if the call to empty returns false.
一般把 “!” 读做 not,if(!vec.empty()) 读做 if notvec.empty(),表示 if vec is not empty。
The Relational Operators Do Not Chain Together
The relational operators (<, <=, >, <=) are left associative. The fact that they are left associative is rarely of any use because the relational operators return bool results. If we do chain these operators together, the result is likely to be surprising:
-
- if (i < j < k) { }
As written, this expression will eva luate as true if k is greater than one! The reason is that the left operand of the second less-than operator is the true/false result of the first—that is, the condition compares k to the integer values of 0 or 1.
To accomplish the test we intended, we must rewrite the expression as follows:
- if (i < j && j < k) { }
Equality Tests and the bool Literals
As we’ll see in Section 5.12.2 (p. 180) a bool can be converted to any arithmetic type—the bool value false converts to zero and true converts to one.
Because bool converts to one, is almost never right to write an equality test that tests against the bool literal true:
- if (val == true) { }
Either val is itself a bool or it is a type to which a bool can be converted. If val is a bool, then this test is equivalent to writing
- if (val) { }
which is shorter and more direct (although admittedly when first learning the language this kind of abbreviation can be perplexing).
More importantly, if val is not a bool, then comparing val with true is equivalent to writing
- if (val == 1) { }
which is very different from
-
- if (val) { }
in which any nonzero value in val is true. If we write the comparison explicitly, then we are saying that the condition will succeed only for the specific value 1.