C++ ยท Chapter 14 of 49

C++ Booleans

The `bool` type holds one of two values: `true` or `false`, internally stored as 1 or 0. Booleans are the result of comparisons and are used to control the flow of a program.

Any non-zero number is treated as true when converted to bool, and zero is treated as false โ€” this matters when mixing numbers and conditions.

Boolean values

`bool isReady = true;` declares a boolean. Comparisons like `5 > 3` automatically produce a bool result.

Truthy conversions

In an `if` condition, any non-zero int is treated as true. This is a common source of subtle bugs when a variable is accidentally used instead of a real comparison.

Example 1 (cpp)
bool isOpen = true;
std::cout << isOpen;
Output
1

true prints as 1 by default with cout.

Example 2 (cpp)
int x = 5;
if (x) std::cout << "truthy";
Output
truthy

Non-zero integers are treated as true in conditions.

Key points

  • bool holds true or false, stored as 1 or 0.
  • Comparisons produce bool results.
  • Non-zero values are truthy in conditions.
  • std::boolalpha can make cout print 'true'/'false' as words.
๐Ÿ’ก Note: Use `std::cout << std::boolalpha << isOpen;` to print 'true' instead of 1.

๐Ÿ“ Quick Quiz

1. What does cout print for a true bool by default?

2. Which value is treated as false in a condition?

3. What does a comparison like x > y produce?