Boolean in C++

  • Last updated Apr 25, 2024

In C++, a boolean is a data type that can have one of two values: true or false. Boolean values are used to represent binary choices or logical states, making them particularly useful in conditions and decision-making within your code.

Boolean values are essential for controlling program flow through conditional statements, such as if statements, while loops, and more, where you can use the boolean expressions to make decisions based on the state of your program.

Declaration and Initialization

In C++, a boolean data type is defined with the bool keyword. You can declare and initialize boolean variables like this:

bool isTrue = true;  // Declaring and initializing a boolean variable with the value true
bool isFalse = false; // Declare and initializing a boolean variable with the value false

Here's a simple example that demonstrates how to work with boolean data in C++:

#include <iostream>
#include <string>

int main() {
    std::string str1 = "mango";
    std::string str2 = "mango";
    std::string str3 = "apple";

    bool result1 = (str1 == str2); // Returns true if str1 is equal to str2 else returns false
    bool result2 = (str1 == str3); // Returns true if str1 is equal to str2 else returns false
    std::cout << "is str1 equal to str2 = " << result1 << std::endl;
    std::cout << "is str1 equal to str3 = " << result2 << std::endl;
    return 0;
}

The output of the above code is as follows:

is str1 equal to str2 = 1
is str1 equal to str3 = 0

In C++, the boolean value true is denoted by 1, while the boolean value false is denoted by 0.