liveBook · Manning

Boolean

As explained in 100 C++ Mistakes and How to Avoid Them

A Boolean value represents one of two logical states, conventionally false and true.

A Boolean represents one of two logical states: false or true. Treating it as an integer creates legal but meaningless operations: incrementing a value does not express toggling, and assigning 42 obscures intent. Prefer the built-in bool type and change states explicitly with negation. section 5.2 section 5.5

Listing 5.9 Simulating Boolean values in an integer
const int TRUE = 1;
const int FALSE = 0;
int main() {
    int truth = FALSE;
    std::cout << "truth is " << (truth ? "real" : "illusory") << "\n";
    ++truth;                                                  #1
    std::cout << "truth is " << (truth ? "real" : "illusory") << "\n";
    truth = 42;                                               #2
    std::cout << "truth is " << (truth ? "real" : "illusory") << "\n";
    return 0;
}

Compare integer-based truth values with the explicit bool form; the listing makes accidental incrementing and arbitrary assignment visible. section 5.5

Use Boolean values in ways that preserve their meaning:

  • Declare state with bool truth = false rather than int truth = 0. section 5.5
  • Toggle explicitly with truth = !truth; do not increment a Boolean. section 5.2 section 5.5
  • Return a predicate's computation directly when it already produces true or false. section 12.4

Make the predicate say exactly what it computes

Instead of storing and assigning a temporary result through an if/else chain, write: bool isEven(int n) { return n % 2 == 0; } This shorter form preserves the same behavior while making the returned Boolean relationship immediately clear. section 12.4

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Explains integer and enumeration substitutes, compiler-level bool representation, misuse risks, and direct predicate returns, but avoids deeper implementation details.
Examples
Demonstrates macro-defined truth values, integer and enumeration simulations, bool misuse, toggling, and an isEven predicate.
What you can do after
Apply bool declarations, explicit negation, and direct predicate returns to produce clearer and safer C++ code.
How it connects
Connects Boolean values with integers, enumerations, macros, predicates, conditional expressions, and if/else structures.

Also explained in

Compare how 11 books explain boolean →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.