8A. Boolean Expressions


Booleans

There are just two values of type bool: true and false. They are used as the values of expressions that have yes-or-no answers.


Comparisons

Use the following operators to compare numbers.

x == y

True if x and y are the same value.

x != y

True if x and y are not the same value.

x > y

True if x is greater than y.

x < y

True if x is less than y.

x >= y

True if x is greater than or equal to y.

x <= y

True if x is less than or equal to y.


Boolean operators

!x

This is true if x is false, and false if x is true.

x && y

This is true if both x and y are true, and false if either of them is false.

If x is false, then y is not evaluated at all. For example, expression

  3 > 4 && max(z,w) == w
does not compute max(z,w) or ask whether its result is equal to w.


x || y

This is true if either x is true or y is true or both are true.

If x is true, then y is not evaluated.



Precedence

Here is a list of the operators that we have seen, from highest to lowest precedence. Those listed together have the same precedence. Operators of the same precedence are done from left to right.

!, unary -
*, /, %
+, binary -
<, >, >=, <=
==, !=
&&
||

Boolean values are actually integers

Java type boolean has only the two values, true and false. C++ is different from Java in that type bool is actually equivalent to type int. Constant true is 1 and constant false is 0.

It is considered good practice, though, to write true and false in your program for boolean values rather than 1 and 0. The coding standards for this course require you to do that.

Whenever an integer value is tested to see whether it is true of false, 0 is considered to be false and all other integers are considered be true. Operators !, && and || always yield either 0 or 1. For example, expression 3 && −2 yields true.


Summary

Values true and false have type bool. Comparisons and Boolean operators are the same as in Java.

Do not make up your own comparisons. !> and !< are not C++ comparison operators.


Exercises

  1. What is the value of expression 4 > 3? Answer

  2. What is the value of expression 6 >= 9? Answer

  3. What is the value of expression 3 > 4 || 6 >= 9? Answer

  4. What is the value of expression 2 == 2 && 5 >= 3? Answer

  5. What is the value of expression !(3 == 3)? Answer