Selections in C++: Logical Operators

The logical operators !, &&, and || can be used to create a compound Boolean expression.

Sometimes, a combination of several conditions determines whether a statement is executed. You can use logical operators to combine these conditions. Logical operators, also known as Boolean operators, operate on Boolean values to create a new Boolean value. Table 3.3 gives a list of Boolean operators. Table 3.4 defines the not (!) operator. The not (!) operator negates true to false and false to true. Table 3.5 defines the and (&&) operator. The and (&&) of two Boolean operands is true if and only if both operands are true. Table 3.6 defines the or (||) operator. The or (||) of two Boolean operands is true if at least one of the operands is true.

Listing 3.5 gives a program that checks whether a number is divisible by 2 and 3, by 2 or 3, and by 2 or 3 but not both:

Listing 3.5 TestBooleanOperators.cpp

1 #include <iostream>

2 using namespace std;

3

4 int main()

5 {

6    int number;

7    cout << “Enter an integer: “;

8    cin >> number;

9

10    if (number % 2 == 0 && number % 3 == 0)

11    cout << number << ” is divisible by 2 and 3.” << endl;

12

13    if (number % 2 == 0 || number % 3 == 0)

14    cout << number << ” is divisible by 2 or 3.” << endl;

15

16    if ((number % 2 == 0 || number % 3 == 0) &&

17    !(number % 2 == 0 && number % 3 == 0))

18    cout << number << ” divisible by 2 or 3, but not both.” << endl;

19

20    return 0;

21 }

(number % 2 == 0 && number % 3 == 0) (line 10) checks whether the number is divisible by 2 and 3. (number % 2 == 0 || number % 3 == 0) (line 13) checks whether the number is divisible by 2 or 3. So, the Boolean expression in lines 16-17

((number % 2 == 0 || number % 3 == 0) &&

!(number % 2 == 0 && number % 3 == 0))

checks whether the number is divisible by 2 or 3 but not both.

If one of the operands of an && operator is false, the expression is false; if one of the operands of an || operator is true, the expression is true. C++ uses these properties to improve the performance of these operators. When evaluating pi && p2, C++ evaluates pi and, if it is true, evaluates p2 otherwise it does not evaluate p2. When evaluating pi || p2, C++ evaluates pi and, if it is false, evaluates p2; otherwise it does not evaluate p2. Therefore, we refer to && as the conditional or short-circuit AND operator and to || as the conditional or short-circuit OR operator. C++ also provides the bitwise AND (&) and OR (|) operators, which are covered in Supplement IV.J and IV.K for advanced readers.

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *