Relational operators are used for comparisons to determine when two numbers are equal or one is greater or less than the other.
Every relational expression returns either true or false.
The? relational operators are presented in the following table.
Name | Operator | Sample | Evaluates |
---|---|---|---|
Equals | == | 100 == 50; | false |
50 == 50; | true | ||
Not equal | != | 100 != 50; | true |
50 != 50; | false | ||
Greater than | > | 100 > 50; | true |
50 > 50; | false | ||
Greater than or equals | >= | 100 >= 50; | true |
50 >= 50; | true | ||
Less than | < | 100 < 50; | false |
50 < 50; | false | ||
Less than or equals | <= | 100 <= 50; | false |
50 <= 50; | true |
Each comparison in C++ is a bool type expression with a value of true or false.
The following expression results in the value true when ASCII code is used.
'A' < 'a' // true, since 65 < 97
Operator | Significance |
---|---|
< | less than |
<= | less than or equal to |
> | greater than |
>= | greater than or equal to |
== | equal |
!= | unequal |
Examples for comparisons:
Comparison | Result |
---|---|
5 >= 6 | false |
1.7 < 1.8 | true |
4 + 2 == 5 | false |
2 * 4 != 7 | true |
Precedence | Operator |
---|---|
High | arithmetic operators < <= > >= == != |
Low | assignment operators |
Relational operators have lower precedence than arithmetic operators but higher precedence than assignment operators.
bool flag = index < max - 1;
In our example, max - 1 is evaluated first, then the result is compared to index, and the value of the relational expression is assigned to the flag variable.
int result;
result = length + 1 == limit;
length + 1 is evaluated first, then the result is compared to limit, and the value of the relational expression is assigned to the result variable.
Since result is an int type, a numerical value is assigned instead of false or true, i.e. 0 for false and 1 for true.
It is OK to assign a value before performing a comparison.
(result = length + 1) == limit
Our example stores the result of length+1 in the variable result and then compares this expression with limit.