← C++ from Scratch
Lesson 13 of 62 · 10 XP
The bool type
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
bool holds true or false. It's the result of any comparison and logical expression:
bool hasKey = true;
int level = 7;
bool canOpen = hasKey && level >= 5; // true
bool locked = !canOpen; // false
std::cout << canOpen << '\n'; // 1 — by default a bool is printed as a number
std::cout << std::boolalpha << canOpen << '\n'; // true
Short-circuiting: in a && b, the expression b isn't evaluated if a is false; in a || b — if a is true.
People rely on this: if (p != nullptr && p->alive) — first the check, then the access.
Task. A year is a leap year if it's divisible by 4 but not by 100, or if it's divisible by 400. Read a year and print
true or false (using std::boolalpha).
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.