C++ provides the ! (logical NOT, also called logical negation) operator to “reverse” a condition’s meaning. The unary logical negation operator has only a single condition as an operand. The unary logical negation operator is placed before a condition when we are interested in choosing a path of execution if the original condition (without the logical negation operator) is false
, such as in the following program segment:
if ( !( grade == sentinelValue ) )
cout << "The next grade is " << grade << endl;
The parentheses around the condition grade == sentinelValue
are needed because the logical negation operator has a higher precedence than the equality operator.
You can often avoid the !
operator by using an appropriate relational or equality operator. For example, the preceding if
statement also can be written as follows:
if ( grade != sentinelValue )
cout << "The next grade is " << grade << endl;
This flexibility often can help you express a condition in a more “natural” or convenient manner. Figure 5.17 is a truth table for the logical negation operator (!
).