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
true
orfalse
.
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
isRaining
is declared as abool
and initialized totrue
. - The
if
statement 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
isAdult
andhasTicket
are declared asbool
, with valuestrue
andfalse
, respectively. - The condition
isAdult && hasTicket
evaluates tofalse
becausehasTicket
isfalse
. - The
else
block 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
num
is initialized to0
. - In the
if
statement,num
is implicitly converted to a Boolean. Since0
is equivalent tofalse
, theelse
block executes.
Key Points about bool
Keyword
- The
bool
keyword represents the Boolean data type in C++. - A
bool
variable can only store two values:true
orfalse
. - Booleans are commonly used in conditional statements and logical operations.
- Integers are implicitly convertible to
bool
in C++, where0
isfalse
and any non-zero value istrue
. - The Boolean data type enhances code readability and logical correctness.