In addition to the arithmetic operators, C++ provides a variety of other operators. Six of these allow two values to be compared, and produce a boolean (i.e. true/false) value indicating their relationship.
| == | equality, returns true if and only if its operands are equal |
| != | inequality, returns true if and only if its operands are different |
| < | less-than, returns true if and only if its left operand is less-than its right operand |
| > | greater-than, returns true if and only if its left operand is greater-than its right operand |
| <= | less-than-or-equal-to, returns true if and only if its left operand is not greater than its right operand |
| >= | greater-than-or-equal-to, returns true if and only if its left operand is not less than its right operand |
In C++, a true/false value is represented by the bool type, so these operators produce a bool value. Since they are used to identify the relationship between two values, they are called the relational operators.
Assuming that i is 11 and j is 22, complete the following table. In the middle column, use the descriptions above to predict the results of each comparison. Then modify express.cpp to display the result of each comparison, and record those results in the rightmost column. (You will need to parenthesize the relational expression within the output statement in order for it to work correctly.)
| Comparison | Prediction | Observation | Comparison | Prediction | Observation |
|---|---|---|---|---|---|
| i == j | i != j | ||||
| i < j | i >= j | ||||
| i > j | i <= j |
To get a boolean expression to display as true or false, it may be necessary to use the boolalpha manipulator. For example:
cout << boolalpha << (i == j) << endl; cout << (i == j) << endl;Try these statements, to see if C++ actually represents booleans differently from the values trueand false.
The relational operators can be used to compare two double (i.e., real) values. However, real equality comparisons should be used with caution, since the machine representation of reals may be inexact.
From this exercise, you should now know how to compare two values and determine their relationship. You should also understand that C++ represents the boolean values false and true with the integers zero and one, respectively. It does this so that a boolean can be accessed just as fast as a number.
Forward to the Next Experiment