|
||||
|
Section 29:
|
[29.13] I can understand the and (&&) and or (||) operators, but what's the purpose of the not (!) operator?
Some people are confused about the ! operator. For example, they think that !true is the same as false, or that !(a < b) is the same as a >= b, so in both cases the ! operator doesn't seem to add anything. Answer: The ! operator is useful in boolean expressions, such occur in an if or while statement. For example, let's assume A and B are boolean expressions, perhaps simple method-calls that return a bool. There are all sorts of ways to combine these two expressions: if ( A && B) ... if (!A && B) ... if ( A && !B) ... if (!A && !B) ... if (!( A && B)) ... if (!(!A && B)) ... if (!( A && !B)) ... if (!(!A && !B)) ...Along with a similar group formed using the || operator. Note: boolean algebra can be used to transform each of the &&-versions into an equivalent ||-version, so from a truth-table standpoint there are only 8 logically distinct if statements. However, since readability is so important in software, programmers should consider both the &&-version and the logically equivalent ||-version. For example, programmers should choose between !A && !B and !(A || B) based on which one is more obvious to whoever will be maintaining the code. In that sense there really are 16 different choices. The point of all this is simple: the ! operator is quite useful in boolean expressions. Sometimes it is used for readability, and sometimes it is used because expressions like !(a < b) actually are not equivalent to a >= b in spite of what your grade school math teacher told you. |
|||