C++ Relational Operators
In this page:
Equality and Inequality
== checks whether two values are equal and != checks whether they're different, and both always produce a boolean result (true or false) rather than the values themselves. A very common beginner mistake is writing a single = instead of == inside a condition, which silently assigns instead of compares.
Example: Equality and Inequality
#include <iostream>
int main() {
int a = 5, b = 3;
std::cout << (a == b) << std::endl;
std::cout << (a != b) << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Greater than and Less than
> and < test whether the left-hand value is strictly greater than or strictly less than the right-hand value, which is strict in the sense that equal values evaluate to false for both. These are the basis for sorting logic and range checks throughout C++ code.
Example: Greater than and Less than
#include <iostream>
int main() {
std::cout << (5 > 3) << std::endl;
std::cout << (5 < 3) << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Greater than or Equal, and Less than or Equal
>= and <= extend > and < to also accept equality, so x >= 5 is true whenever x is 5 or anything larger. Choosing between the strict and inclusive versions correctly is critical for avoiding off-by-one errors, especially in loop bounds and array index checks.
Example: Greater than or Equal, and Less than or Equal
#include <iostream>
int main() {
int x = 5;
std::cout << (x >= 5) << std::endl; // true: equal counts
std::cout << (x <= 4) << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Relational Checks on Numbers
Relational operators are what give if statements their decision-making power — an expression like if (score >= passingGrade) evaluates to true or false and determines which branch of code actually runs. Nearly every piece of conditional logic in a real C++ program is built from combinations of these comparisons.
Example: Relational Checks on Numbers
#include <iostream>
int main() {
int score = 75, passingGrade = 60;
if (score >= passingGrade) {
std::cout << "Passed" << std::endl;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Relational Checks on Characters
Comparing char values compares their underlying ASCII numeric codes, so a < b is true because a has a smaller code than b, and importantly, all uppercase letters have smaller codes than all lowercase letters, meaning Z < a is also true. This ASCII-based ordering is why naive alphabetical sorting of mixed-case text can produce surprising results unless you normalize case first.
Example: Relational Checks on Characters
#include <iostream>
int main() {
std::cout << ('a' < 'b') << std::endl;
std::cout << ('Z' < 'a') << std::endl; // uppercase codes are smaller
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: