C++ provides logical operators that may be used to form more complex conditions by combining simple conditions. The logical operators are:
The following examples illustrate the use of each logical operator.
When the AND operator, &&, is used with two simple expressions, the condition is true only if both individual expressions are true by themselves. Thus the compound condition
if ( ( age > 40 ) && ( term < 10 ) ) { cout << "age is greater than 40 AND" cout << "term is less than 10" }
is read as "if age is greater than 40 AND term is less than 10". This condition is true (has a non-zero value) only if age is greater than 40 and term is less than 10.
The logical OR operator, ||, is also applied between two expressions. When using the OR operator, the condition is satisfied if either one or both of the two expressions is true. Thus the compound condition
if ( ( age > 40 ) || ( term < 10 ) ) { cout << "age is greater than 40 OR" cout << "term is less than 10" }
will be true if either age is greater than 40, term is less than 10, or both conditions are true.
The NOT operator is used to change an expression to its opposite state; that is, if the expression has any nonzero value (true), !expression produces a zero value (false). If an expression is false to begin with (has a zero value), !expression is true and evaluates to 1. For example, assuming the object age has a value of 26, the expression ( age > 40 ) has a value of zero (it is false), while the expression !( age > 40 ) has a value of 1.
if !( age > 40 ) cout << "age is NOT greater than 40"
Assume:
i = 2, j = 7, k = 6, and m = 1
What does each of the following statements print?
cout << ( i == 10 ) << endl;
cout << ( j == 7 ) << endl;
cout << ( i >= 6 && j < 2 ) << endl;
cout << ( m <= 1 && k < m ) << endl;
cout << ( j >= i || k == m ) << endl;
cout << ( k + m < j || 4 - j >= k ) << endl;
cout << ( ! m ) << endl;
cout << ( !( j - m ) ) << endl;
cout << ( !( k > m ) ) << endl;