CodeBlanks Logo Icon CodeBlanks

Comparison operators

Learn to compare values with ==, !=, <, >, <= and >=.

Comparison operators

Comparison operators compare two values and return a bool (true/false). Six operators: == (equal), != (not equal), < (less), > (greater), <= (less or equal), >= (greater or equal).

Note: == is comparison, = is assignment. if (x == 5) checks whether x equals 5; if (x = 5) assigns 5 to x and is always true. This is a very common mistake.

Since the result is bool, it can be stored in a variable: bool same = (a == b);. When printed with std::cout, true shows as 1, false as 0.

Comparison results

A comparison result is true or false. std::cout prints them as 1 and 0. To see the text true/false, use std::boolalpha.

Examples: 5 < 10 → true, 5 > 10 → false, 5 == 5 → true, 5 != 5 → false.

Comparisons are mostly used in if conditions: if (age >= 18). But they can also be assigned to a variable and used later. This is useful for breaking down complex conditions.

Practice Print comparison results

Inside main, declare int a = 10; and int b = 20;. Perform two comparisons: bool first = a < b; and bool second = a == b;. Print both on separate lines with std::cout using std::endl.

Starter code

main.cpp
#include <iostream>

int main() {
    // Declare a and b
    // Do two comparisons and print them
    return 0;
}

Sample solution

main.cpp
#include <iostream>

int main() {
    // Declare a and b
    int a = 10;
    int b = 20;
    // Do two comparisons and print them
    bool first = a < b;
    bool second = a == b;
    std::cout << first << std::endl;
    std::cout << second << std::endl;
    return 0;
}

Expected output

1
0

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Equality comparison

Question
bool same = (a ____ b);
Answer
bool same = (a == b);

Explanation: == is the equality comparison.

2 What is the result of 5 != 3?

  • 0 (false)
  • 3
  • 1 (true) Correct answer
  • 5

Explanation: 5 and 3 are not equal, so the result is true (1).

3 Match comparison operators

Term Meaning
== Equal
!= Not equal
< Less
>= Greater or equal

All lessons in Beginner