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 or false.

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:

  1. The variable isRaining is declared as a bool and initialized to true.
  2. The if statement checks the value of isRaining. Since it is true, 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:

  1. The variables isAdult and hasTicket are declared as bool, with values true and false, respectively.
  2. The condition isAdult && hasTicket evaluates to false because hasTicket is false.
  3. 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:

  1. The integer variable num is initialized to 0.
  2. In the if statement, num is implicitly converted to a Boolean. Since 0 is equivalent to false, the else block executes.

Key Points about bool Keyword

  1. The bool keyword represents the Boolean data type in C++.
  2. A bool variable can only store two values: true or false.
  3. Booleans are commonly used in conditional statements and logical operations.
  4. Integers are implicitly convertible to bool in C++, where 0 is false and any non-zero value is true.
  5. The Boolean data type enhances code readability and logical correctness.