← Back to C++ Course | Chapter 3: Operators | Lesson 3 of 9

C++ Relational Operators

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

cpp
#include <iostream>

int main() {
	int a = 5, b = 3;
	std::cout << (a == b) << std::endl;
	std::cout << (a != b) << std::endl;
	return 0;
}

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

cpp
#include <iostream>

int main() {
	std::cout << (5 > 3) << std::endl;
	std::cout << (5 < 3) << std::endl;
	return 0;
}

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

cpp
#include <iostream>

int main() {
	int x = 5;
	std::cout << (x >= 5) << std::endl; // true: equal counts
	std::cout << (x <= 4) << std::endl;
	return 0;
}

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

cpp
#include <iostream>

int main() {
	int score = 75, passingGrade = 60;
	if (score >= passingGrade) {
		std::cout << "Passed" << std::endl;
	}
	return 0;
}

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

cpp
#include <iostream>

int main() {
	std::cout << ('a' < 'b') << std::endl;
	std::cout << ('Z' < 'a') << std::endl; // uppercase codes are smaller
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.