Comparison
Operators in C++
Learn how to use comparison operators to form boolean expressions that evaluate to true or false: the foundation of decision-making in every C++ program.
What Is a Boolean Expression?
A boolean expression is any expression that evaluates to one of exactly two values: true or false. In C++, these map to the integer values 1 (true) and 0 (false).
The Six Comparison Operators
How a Comparison Evaluates
The compiler evaluates the expression left operand, then operator, then right operand, and produces a single bool result.
Core Rule: Syntax and Return Type
Operator Reference Table
| Operator | Meaning | Example | Result |
|---|---|---|---|
| \(\texttt{==}\) | Equal to | \(\texttt{5 == 5}\) | true |
| \(\texttt{!=}\) | Not equal to | \(\texttt{5 != 3}\) | true |
| \(\texttt{<}\) | Less than | \(\texttt{3 < 7}\) | true |
| \(\texttt{>}\) | Greater than | \(\texttt{3 > 7}\) | false |
| \(\texttt{<=}\) | Less than or equal | \(\texttt{4 <= 4}\) | true |
| \(\texttt{>=}\) | Greater than or equal | \(\texttt{2 >= 9}\) | false |
\(\texttt{==}\) versus \(\texttt{=}\): The Critical Difference
How to Apply Comparison Operators
Example 1: Simple if Statement
Example 2: Loop Condition
Notice: using \(<\) instead of \(\le\) would print only 1 2 3 4, missing the last value. The boundary operator you choose matters.
Example 3: Chaining with Logical Operators
Key insight: You cannot write the mathematical expression \( 70 \le \texttt{score} < 90 \) directly in C++. You must explicitly use two separate comparisons connected by \(\texttt{&&}\).
Comparing Characters
In C++, char values are compared by their ASCII codes. Letters later in the alphabet have higher codes. Uppercase and lowercase letters occupy different ranges.
Floating-Point Pitfall
Common Mistakes
Summary at a Glance
| Concept | Key Point | Example |
|---|---|---|
| Return type | Always bool | true / false |
| Equality | Use ==, not = | \(\texttt{x == 5}\) |
| Boundary | \(\texttt{<=}\) includes the endpoint | \(\texttt{count <= 10}\) |
| Range check | Use && with two operators | \(\texttt{x >= 1 \&\& x <= 100}\) |
| Floats | Avoid == on doubles | \(\texttt{abs(a - b) < 1e-9}\) |
| Characters | Compared by ASCII code | \(\texttt{'a' < 'z'}\) is true |
Question 1 of 5
What does the following expression evaluate to?
\(\texttt{7 != 7}\)
Question 2 of 5
Which line correctly checks if the variable temp is greater than or equal to 100?
Question 3 of 5
What is the value of result after this code runs?int x = 4;
bool result = (x \(\texttt{<}\) 4);
Question 4 of 5
A student writes: \(\texttt{if (1 < x < 10)}\) intending to check that x is between 1 and 10. What actually happens?
Question 5 of 5
Why is it dangerous to use \(\texttt{==}\) to compare two double values in C++?