Programming C++  «Prev  Next»
Lesson 6Bool expressions
ObjectiveUnderstand how C++ treats boolean expressions.

C++ Boolean Expressions

Operators and expression forms in C++ are largely the same as in C. One difference is that relational, equality, and logical expressions evaluate as bool expressions.
In contemporary C++ systems, the boolean values true and false are used to direct the flow of control in the various statement types.

Each of these operators compares two values and results in a value of type bool; there are only two possible bool values, true and false. true and false are keywords and are literals of type bool.
They are sometimes called Boolean literals . If you cast true to an integer type, the result will be 1; casting false to an integer results in 0.
You can also convert numerical values to type bool. Zero converts to false, and any nonzero value converts to true. When you have a numerical value where a bool value is expected, the compiler will insert an implicit conversion to convert the numerical value to type bool. This is very useful in decision-making code. You create variables of type bool just like other fundamental types. Here is an example:
bool isValid {true}; // Define, and initialize a logical variable

This defines the variable isValid as type bool with an initial value of true.

Applying the Comparison Operators

You can see how comparisons work by looking at a few examples. Suppose you have integer variables i and j, with values 10 and -5 respectively. Consider the following expressions:
i > j i != j j > -8 i <= j + 15

All of these expressions evaluate to true. Note that in the last expression, the addition, j + 15, executes first because + has a higher precedence than <=. You could store the result of any of these expressions in a variable of type bool. For example:
isValid = i > j;

If i is greater than j, true is stored in isValid, otherwise false is stored. You can compare values stored in variables of character types, too. Assume that you define the following variables:
char first {'A'};
char last {'Z'};

You can write comparisons using these variables:
first < last 'E' <= first first != last

Here you are comparing code values. The first expression checks whether the value of first, which is 'A', is less than the value of last, which is 'Z'. This is always true. The result of the second expression is false, because the code value for 'E' is greater than the value of first. The last expression is true, because 'A' is definitely not equal to 'Z'.
Relational, equality, and logical operators operate on expressions and yield either the bool value false or the bool value true. This differs from the C convention of treating zero as false and nonzero as true because no bool type exists in C.