C++ bool Keyword
The bool keyword in C++ represents the Boolean data type, which can store one of two possible values: true or false. It is primarily used in conditional statements and logical operations to control program flow.
The bool type improves code readability and allows for cleaner logical comparisons compared to older techniques using integers (e.g., 0 for false and non-zero for true).
Syntax
</>
Copy
bool variable_name = true_or_false;
- bool
- The keyword for declaring a Boolean variable.
- variable_name
- The name of the Boolean variable being declared.
- true_or_false
- The initial value assigned to the variable, which must be either
trueorfalse.
Examples
Example 1: Declaring and Using a Boolean Variable
This example demonstrates how to declare a Boolean variable and use it in a conditional statement.
</>
Copy
#include <iostream>
using namespace std;
int main() {
bool isRaining = true;
if (isRaining) {
cout << "Take an umbrella!" << endl;
} else {
cout << "No need for an umbrella." << endl;
}
return 0;
}
Output:
Take an umbrella!
Explanation:
- The variable
isRainingis declared as abooland initialized totrue. - The
ifstatement checks the value ofisRaining. Since it istrue, the message “Take an umbrella!” is printed.
Example 2: Boolean Operations
This example demonstrates how Boolean variables can be used in logical operations.
</>
Copy
#include <iostream>
using namespace std;
int main() {
bool isAdult = true;
bool hasTicket = false;
if (isAdult && hasTicket) {
cout << "You can enter the event." << endl;
} else {
cout << "Entry denied." << endl;
}
return 0;
}
Output:
Entry denied.
Explanation:
- The variables
isAdultandhasTicketare declared asbool, with valuestrueandfalse, respectively. - The condition
isAdult && hasTicketevaluates tofalsebecausehasTicketisfalse. - The
elseblock executes, printing “Entry denied.”
Example 3: Converting Integer to Boolean
This example shows how integers are implicitly converted to Boolean values in C++.
</>
Copy
#include <iostream>
using namespace std;
int main() {
int num = 0;
if (num) {
cout << "Non-zero value is true." << endl;
} else {
cout << "Zero value is false." << endl;
}
return 0;
}
Output:
Zero value is false.
Explanation:
- The integer variable
numis initialized to0. - In the
ifstatement,numis implicitly converted to a Boolean. Since0is equivalent tofalse, theelseblock executes.
Key Points about bool Keyword
- The
boolkeyword represents the Boolean data type in C++. - A
boolvariable can only store two values:trueorfalse. - Booleans are commonly used in conditional statements and logical operations.
- Integers are implicitly convertible to
boolin C++, where0isfalseand any non-zero value istrue. - The Boolean data type enhances code readability and logical correctness.
