Comparing Values

Before a program can make decisions, it needs to ask questions like “is the age at least 18?”. In C++ these questions are made with comparison operators. The answer is always true or false – a bool.

OperatorQuestionExampleResult
==equal to?5 == 5true
!=not equal to?5 != 3true
<less than?2 < 8true
>greater than?2 > 8false
<=less than or equal?4 <= 4true
>=greater than or equal?3 >= 9false
#include <iostream>
using namespace std;

int main() {
    int age = 20;
    cout << boolalpha;            // print true/false as words
    cout << (age >= 18) << "\n";
    cout << (age == 21) << "\n";
    cout << (age != 21) << "\n";
    return 0;
}

Output

true
false
true

Common mistake: = and == are different! = puts a value in a variable. == asks if two values are equal.

Strings can be compared too. == checks if two texts are exactly the same (capital letters count!):

#include <iostream>
#include <string>
using namespace std;

int main() {
    string password = "dragon";
    cout << boolalpha;
    cout << (password == "dragon") << "\n";
    cout << (password == "Dragon") << "\n";
    return 0;
}

Output

true
false
HOME LABS COMMUNITY DASHBOARD