Codiqo

Learn C++ · lesson 10 of 61 · about 7 minutes

Comparisons and bool

Let the adventure remember which way the hero went: compare values, store the answer in a bool, and print it as true or false.

What you'll learn

  • Use the six comparison operators
  • Store results in bool variables
  • Print bools with std::boolalpha

Yes-or-no questions

Your hero has picked a path, and the story needs to know which one. A comparison asks a question like that and gives a bool: true or false.

| Operator | Asks |
|---|---|
| == | equal? |
| != | not equal? |
| < > | less, more? |
| <= >= | at most, at least? |

== compares two values. A single = stores a value.

Comparisons give a bool

#include <iostream>

int main() {
    int gold = 5;
    bool rich = gold >= 10;
    std::cout << rich << "\n";
    std::cout << std::boolalpha << rich << "\n";
    std::cout << (gold != 0) << "\n";
}

Output

0
false
true

Printing bools

std::cout prints a bool as 1 or 0 until you send it std::boolalpha. After that it stays on for the rest of the program, which is why every bool in your adventure prints as a word.

Put a comparison in brackets when you print it: std::cout << gold == 5 doesn't compile, because << is worked out before ==.

Comparing strings

#include <iostream>
#include <string>

int main() {
    std::string path = "east";
    std::cout << std::boolalpha;
    std::cout << (path == "east") << "\n";
    std::cout << (path == "East") << "\n";
}

Output

true
false

Tip

Comparing text is exact: East and east are different strings.

Now try it yourself

This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.