In C++, true
is represented as 1.
C++ handles boolean values in a manner consistent with C. This means:
- False: Zero (0) is used to represent
false
. - True: Non-zero values are interpreted as
true
. Importantly,true
is stored as 1.
This is crucial for understanding how C++ handles logical operations and conditional statements.
C++ Boolean Representation
Boolean Value | Integer Representation |
---|---|
true |
1 |
false |
0 |
Examples
#include <iostream>
int main() {
bool myTrueValue = true;
bool myFalseValue = false;
std::cout << "True is stored as: " << myTrueValue << std::endl; // Outputs: True is stored as: 1
std::cout << "False is stored as: " << myFalseValue << std::endl; // Outputs: False is stored as: 0
if (5) { // Any non-zero value is treated as true
std::cout << "5 is considered true." << std::endl; // This line will be executed.
}
if (0) {
std::cout << "0 is considered true." << std::endl; // This line will NOT be executed.
} else {
std::cout << "0 is considered false." << std::endl; // This line will be executed.
}
return 0;
}
Key Takeaways
- C++ retains C-style logic for boolean operations.
- Non-zero integers are interpreted as
true
. - Zero is interpreted as
false
. true
is stored as the integer1
.false
is stored as the integer0
.