Skip to main content

Section 7.10 Simplifying Logical Expressions

Many times, you can express the same logic in multiple ways. We have seen examples of this already. If isEven is a bool variable, these two expressions are equivalent:
if (isEven)
if (isEven == true)
From mathematics, we know that > is the opposite of <=. So these two expressions are also equivalent:
if (x > 5)
if (!(x <= 5))
In both of those cases, the first expression is easier to write and read and should be favored. If you find yourself writing something complex, stop and think about whether there is a simpler but logically equivalent expression.

Checkpoint 7.10.1.

Sometimes you need to negate an expression containing a mix of relational and logical operators. For example, to test if x and y are both nonzero, you could write the following:
if (!(x == 0 || y == 0)) {
    cout << "Neither x nor y is zero\n";
}
This condition is difficult to read because of the ! and parentheses. A better way to negate logic expressions is to apply De Morganโ€™s laws :
In words, negating a logical expression is the same as negating each term and changing the operator. The ! operator takes precedence over && and ||, so you donโ€™t have to put parentheses around the individual terms !A and !B.
De Morganโ€™s laws also apply to the relational operators. In this case, negating each term means using the โ€œoppositeโ€ relational operator:
It may help to read these examples out loud in English. For instance, โ€œIf I donโ€™t want the case where \(x\) is less than 5 and \(y\) is 3, then I need \(x\) to be greater than or equal to 5, or I need \(y\) to be anything but 3.โ€
Returning to the previous example, here is the revised condition. In English, it reads, โ€œIf \(x\) is not zero and \(y\) is not zero.โ€ The logic is the same, and the source code is easier to read:
if (x != 0 && y != 0) {
    cout << "Neither x nor y is zero\n";
}
You have attempted of activities on this page.