C++ Relational Operators
In C++, Relational operators are used to compare two values or expressions, and based on this comparison, it returns a boolean value (either true or false) as the result. Generally false is represented as 0 and true is represented as any non-zero value (mostly 1).
Syntax of Relational Operators
All C++ relational operators are binary operators that are used with two operands as shown:
operand1 relational_operator operand2
expression1 relational_operator expression2
There are 6 relational operators in C++ which are explained below with examples:
Table of Content
1. Greater than ( > )
The greater than ( > ) operator returns true if the left operand is greater than the right operand, otherwise, it returns false.
Example:
29 > 21 // returns true
12 > 12 // return false
10 > 57 // return false
2. Less than ( < )
The less than ( < ) operator checks if the left operand is less than the right operand. If it is, it returns true, otherwise, it returns false.
Example:
2 < 21 // returns true
12 < 12 // return false
12 < 5 // return false
3. Greater than or equal to ( >= )
The greater than or equal to ( >= ) operator returns true if the left operand is greater than or equal to the right operand, otherwise, it returns false.
Example:
29 >= 21 // returns true
12 >= 12 // return true
10 >= 58 // return false
4. Less than or equal to ( <= )
The less than or equal to ( <= ) operator returns true if the left operand is less than or equal to the right operand, otherwise, it returns false.
Example:
2 <= 21 // returns true
12 <= 12 // return true
12 <= 5 // return false
5. Equal to ( == )
The equal to ( == ) operator checks if two values are equal. It returns true if the values are equal, otherwise, it returns false.
Example:
9 == 9 // returns true
19 == 12 // return false
6. Not equal to ( != )
The not equal to ( != ) operator checks if two values are not equal. It returns true if the values are different and false if they are equal.
Example:
12 != 21 // returns true
12 != 12 // return false
Code Example
In the below code, we have defined two variables with some integer value and we have printed the output by comparing them using relational operators in C++. In the output, we get 1, 0, 0, 0, and 1 where 0 means false and 1 means true.
#include <iostream>
using namespace std;
int main() {
// Variables for comparison
int a = 10;
int b = 6;
// Greater than
cout << "a > b = " << (a > b) << endl;
// Less than
cout << "a < b = " << (a < b) << endl;
// Equal to
cout << "a == b = " << (a == b) << endl;
// Not equal to
cout << "a != b = " << (a != b);
return 0;
}
Output
a > b = 1 a < b = 0 a == b = 0 a != b = 1