Logical operators
The logical operators and
(&&)
and or
(||)
produce a true or false
based on
the logical relationship of its arguments. Remember that in C and C++, a
statement is true if it has a non-zero value, and false if it has
a value of zero. If you print a bool, you’ll typically see a
‘1’ for true and ‘0’ for
false.
This example uses the relational and
logical operators:
//: C03:Boolean.cpp
// Relational and logical operators.
#include <iostream>
using namespace std;
int main() {
int i,j;
cout << "Enter an integer: ";
cin >> i;
cout << "Enter another integer: ";
cin >> j;
cout << "i > j is " << (i > j) << endl;
cout << "i < j is " << (i < j) << endl;
cout << "i >= j is " << (i >= j) << endl;
cout << "i <= j is " << (i <= j) << endl;
cout << "i == j is " << (i == j) << endl;
cout << "i != j is " << (i != j) << endl;
cout << "i && j is " << (i && j) << endl;
cout << "i || j is " << (i || j) << endl;
cout << " (i < 10) && (j < 10) is "
<< ((i < 10) && (j < 10)) << endl;
} ///:~
You can replace the definition for
int with float or double in the program above. Be aware,
however, that the comparison of a floating-point number with the value of zero
is strict; a number that is the tiniest fraction different from another number
is still “not equal.” A floating-point number that is the tiniest
bit above zero is still
true.