Selections in C++: The bool Data Type

The bool data type declares a variable with the value either true or false.

How do you compare two values, such as whether a radius is greater than 0, equal to 0, or less than 0? C++ provides six relational operators, shown in Table 3.1, which can be used to compare two values (assume radius is 5 in the table).

The result of the comparison is a Boolean value: true or false. A variable that holds a Boolean variable  is known as a Boolean variable. The bool data type is used to declare Boolean variables. For example, the following statement assigns true to the variable lightsOn:

bool lightsOn = true;

true and false are Boolean literals, just like a number such as 10. They are keywords and cannot be used as identifiers in your program.

Internally, C++ uses 1 to represent true and 0 for false. If you display a bool value to the console, 1 is displayed if the value is true and 0 if it is false.

For example,

cout << (4 < 5);

displays 1, because 4 < 5 is true.

cout << (4 > 5);

displays 0, because 4 > 5 is false.

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *