What are Boolean values in C++?

Overview

Boolean values in C++ tell us whether a given expresson is true, i.e. 1, or false, i.e. 0.

A Boolean variable is one that is declared with the bool keyword. This type of variable can only take either true or false as its value.

Code example

#include <iostream>
using namespace std;
int main() {
// creating bool variables
bool iLoveCoding = true;
bool iLoveCrayfish = false;
// returning a boolean value
cout << iLoveCoding << "\n";
cout << iLoveCrayfish;
return 0;
}

Code explanation

Here is a line-by-line explanation of the code above:

  • Lines 6-7: We create Boolean variables, iLoveCoding and iLoveCrayfish, and assign a Boolean value to each of them.

  • Lines 10-11: We return and print our variables.

It is worth noting that a true value will return 1 and a false value will return 0.

Returning Boolean values from Boolean expressions

A Boolean expression in C++ is that type of expression that will return a Boolean value: either 1 (true) or 0 (false).

When we write a Boolean expression to compare two values in C++ using the comparison operator, the return value is a Boolean.

Example

#include <iostream>
using namespace std;
int main() {
// greater than operator
cout <<"(1 > 2) = " << (1 > 2)<< "\n";
// less than operator
cout <<"(1 < 2) = " << (1 < 2)<< "\n";
// equal to operator
cout <<"(1 == 2) = " << (1 == 2)<< "\n";
// not equal to operator
cout <<"(1 != 2) = " << (1 != 2)<< "\n";
// greater than or equal to operator
cout <<"(1 >= 2) = " << (1 >= 2)<< "\n";
// less than or equal to operator
cout <<"(1 <= 2) = " << (1 <= 2);
return 0;
}

Code explanation

From the output of the code above, we can see that the expressions which are true (e.g., (1<2)) return 1, while the expressions which are false ( e.g., (1>2)) return 0.

Free Resources