This is a really interesting question that goes back to how computers fundamentally work with true and false values. Let's break it down:
In early computers, there was no special boolean type - programmers used regular numbers to represent true and false. They needed a consistent rule for which numbers meant true and which meant false. The simplest rule was:
0
means false
(nothing, absence of a value)true
(presence of a value)This tradition carried forward into C, and then into C++, even after C++ added the bool
 type.
This convention actually turns out to be really useful in practice. Here's an example:
#include <iostream>
using namespace std;
int main() {
int PlayerHealth{100};
// We can use PlayerHealth directly in an
// if statement
if (PlayerHealth) {
cout << "Player is alive!\n";
}
// Later in the game, player takes damage...
PlayerHealth = 0;
if (PlayerHealth) {
cout << "Player is alive!";
} else {
cout << "Game Over!";
}
}
Player is alive!
Game Over!
In this example, we can check if the player is alive just by checking if their health is non-zero. We don't need to write if (PlayerHealth > 0)
- though that would work too!
This pattern shows up in many real-world programming scenarios:
The pattern is so useful that many modern programming languages have adopted it, even ones that weren't based on C or C++.
Answers to questions are automatically generated and may not have been reviewed.
Going into more depth on what is happening when a variable is used as a different type