Skip to main content

Section 7.2 Relational Operators

The most common way to produce a boolean value is by using a relational operator (also known as comparison operator) to compare two values.
C++ has six relational operators that test the relationship between two values (e.g., whether they are equal, or whether one is greater than the other). The following expressions show how they are used:
Listing 7.2.1.
Each comparison represents a questions. x == y asks the question β€œdoes x equal y?”. The comparison operator decides if the answer is true or false and evaluates to that result. (Remember that an output of 1 means true and 0 means false.) In many ways, the == in x == y is similar to + in x + y. They both are operators that use two operands (x and y here) and calculate an answer based on them.
The two sides of a relational operator have to be compatible. For example, the expression 5 < "6" is invalid because 5 is an int and "6" is a string. When comparing values of different numeric types, C++ applies the same conversion rules you saw previously with the assignment operator. For example, when evaluating the expression 5 < 6.2, C++ automatically converts the 5 to 5.0.
Since relational operators evaluate to a boolean value, you can store the result of a comparison into a bool variable:
// A number is even if there is 0 remainder when divided by 2.
bool evenFlag = (x % 2 == 0);  // true if x is even

bool positiveFlag = (x > 0);   // true if x is positive
The parentheses are unnecessary, but they make the code easier to understand. A variable defined in this way is called a flag, because it signals, or β€œflags”, the presence or absence of a condition.

Checkpoint 7.2.1.

Checkpoint 7.2.2.

You have attempted of activities on this page.