How do you use bool in C++?
In C++, bool is a Boolean data type used to represent true or false values. One can use bool in the following way:
- Declare and initialize a boolean variable.
bool isTrue = true;
bool isFalse = false;
- Compare expressions using relational operators.
bool result = (5 > 3); // result的值为true
bool result2 = (10 == 10); // result2的值为true
bool result3 = (7 < 4); // result3的值为false
- Perform logical operations on boolean values using logical operators.
bool a = true;
bool b = false;
bool result = (a && b); // result的值为false (逻辑与)
bool result2 = (a || b); // result2的值为true (逻辑或)
bool result3 = !a; // result3的值为false (逻辑非)
- Using bool as the condition in a conditional statement.
bool isTrue = true;
if (isTrue) {
// 在条件为真时执行的代码
} else {
// 在条件为假时执行的代码
}
- Using bool as the return type of a function:
bool isEven(int num) {
if (num % 2 == 0) {
return true;
} else {
return false;
}
}
Here are some common examples of how to use bool, which can be tailored to fit specific use cases.