C++ Comparison Operators(Relational Operators)
Comparison(Relational) operators are used to compare two values and return a boolean value indicating whether the comparison is true or false. In C++, the comparison operators are:
Operator | Name | Description | Example |
---|---|---|---|
== | Equal to | Returns true if the values on both sides of the operator are equal, otherwise returns false | 5 == 5 returns true |
!= | Not equal to | Returns true if the values on both sides of the operator are not equal, otherwise returns false | 5 != 5 returns false |
> | Greater than | Returns true if the value on the left side of the operator is greater than the value on the right side, otherwise returns false | 5 > 4 returns true |
< | Less than | Returns true if the value on the left side of the operator is less than the value on the right side, otherwise returns false | 5 < 4 returns false |
>= | Greater than or equal to | Returns true if the value on the left side of the operator is greater than or equal to the value on the right side, otherwise returns false | 5 >= 5 returns true |
<= | Less than or equal to | Returns true if the value on the left side of the operator is less than or equal to the value on the right side, otherwise returns false | 5 <= 5 returns true |
Here's an example of using comparison operators in C++ code:
1#include <iostream> 2using namespace std; 3 4int main() { 5 int x = 5, y = 6; 6 cout << (x == y) << endl; // returns false 7 cout << (x != y) << endl; // returns true 8 cout << (x > y) << endl; // returns false 9 cout << (x < y) << endl; // returns true 10 cout << (x >= y) << endl; // returns false 11 cout << (x <= y) << endl; // returns true 12 return 0; 13}
As you can see, the comparison operators return either 0
(false
) or 1
(true
), which can be used in control structures like if
statements to make decisions based on the result of a comparison.