What is boolean in C++?

A boolean data type in C++ is defined using the keyword bool. Usually, 11 (true) and 22 (false) are assigned to boolean variables as their default numerical values. Although any numerical value can be assigned to a boolean variable in C++, all values other than 00 are considered to be true and stored as 11, while 00 is considered to be false. Printing a bool variable on a console displays its numerical value.

Code

#include <iostream>
using namespace std;
int main() {
// true = 1:
bool p = true;
if(p == 1)
cout << "'p' is true." << endl;
// false = 0:
bool q = false;
if(q == 0)
cout << "'q' is false." << endl;
// Every value other than 0 is stored as 1:
bool r = -5;
if(r == 1 && r == true)
cout << "-5 is stored as 1 in 'r' and it is true." << endl;
// 0 is stored as it is:
bool t = 0;
if(!t)
cout << "'t' is false." << endl;
return 0;
}
svg viewer

Using boolean in a numerical expression

A boolean variable in C++ can be used in a numerical expression as well. As mentioned above, if a bool variable is equal to true( or any numeric value other than 00), 11 is assigned to it and taken as 11 during the evaluation of the expression; 00 and false will be taken as 00.

Code

#include <iostream>
using namespace std;
int main() {
bool x = 10; // x = 1;
bool y = false; // y = 0;
// Using bool in a numeric expression:
cout << 2 * (x + y) << endl;
return 0;
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved