A boolean data type in C++ is defined using the keyword bool
. Usually, (true
) and (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 are considered to be true
and stored as , while is considered to be false
. Printing a bool
variable on a console displays its numerical value.
#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;}
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 ), is assigned to it and taken as during the evaluation of the expression; and false
will be taken as .
#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