Operators: Comparison Operators

Learn about the comparison operators in C++ and how to use them.

We'll cover the following

In this lesson, we’ll learn about the C++ comparison operators.

Comparison operators

We use comparison operators to compare two or more values.

We can see the different comparison operators in the image below.

The table below shows comparison operators with examples where x and y can be any value.

One thing to note is that using the comparison operators, the expression either evaluates to 1 if it is true or 0 if it is false.

Comparison Operator

Operators

Meaning

Example

<

Less than

  • 9 < 12 (true/1)
  • 12 < 9 (false/0).

>

Greater than

  • 9 > 12 (false/0)
  • 12 > 9 (true/1)

>=

Greater than equals to

  • 9 >= 12 (false/0)
  • 12 >= 9 (true/1)
  • 12 >= 12 (true/1)

<=

Less than equals to

  • 9 <= 12 (true/1)
  • 12 <= 9 (false/0)
  • 9 <= 9 (true/1)

==

Double equals to

  • 9 == 9 (true/1)
  • 9 == 12 (false/0)

!=

Not equals to

  • 9 != 9 (false/0)
  • 9 != 12 (true/1)

In C++, a nonzero value in any condition is considered true, and a zero is considered as false.

Quiz

Let’s solve the quiz below to check our understanding of the logical, assignment, and comparison operators.

1

If int x = 10, y = 11, a = 10, b = 30 and c = 0, what will be the final value of c, x, and y?

  1. c += (x < y);
  2. c += ((x < y) && (x + y <= b));
  3. c += ((x + 20) < b && (++x <= 11))
A)

c = 1, x = 10, y = 11

B)

c = 2, x = 10, y = 11

Question 1 of 40 attempted