8B. Mental Model of Boolean Expressions

Be careful when translating from English to C++. English allows you to take liberties that C++ does not. Common mathematical notation also allows you to write things that C++ does not allow.

x < y < z

You cannot write combinations of comparisons this way. Write x < y && y < z.

x is 1 or 2

Do not try to write this as x == 1 || 2. Each operand of || is treated as a boolean expression. Expression x == 1 || 2 is the same as (x == 1) || (2), where (2) as a "boolean" value (which is considered to be true). To ask if x is 1 or 2, say x == 1 || x == 2.

x is even

In English, is sometimes means "is equal to", and sometimes means "has the property". For example, "Jumbo is an elephant" does not indicate that "Jumbo" and "an elephant" are the same thing, but that Jumbo has the property of being an elephant.

In C++, some functions, called predicates, yield boolean results. Predicates are used to check for properties. For example, suppose that even is a predicate where even(x) yields true if x is even and false if x is odd.

To use a predicate, treat it like any other function. If you want to ask if x is even, write even(x), as in

  if(even(x))
  {
    ...
  }
Do not write x == even. If you have a function isPrime(x) that returns true if x is prime, then test isPrime(n) works to check whether n is prime. Do not write x == isPrime.


isPrime(n) is true
isPrime(n) is false

To ask if n is prime, just write isPrime(n). Do not write isPrime(n) == true. To test whether n is not prime, write !isPrime(n), not isPrime(n) == false.

Exercises

  1. Give an expression that is equivalent to !(x == y), but that does not use the negation operator, !, and does not mention constant false. Answer

  2. Give an expression that is equivalent to !(x > y), but that does not use the negation operator, !, and does not mention constant false. Answer

  3. Give an expression that is true if x, y and z are all equal to one another. Answer

  4. Give an expression that is equivalent to isPrime(n) == false, but that does not use any comparison operator. Answer

  5. Give a boolean expression that is equivalent to x < y || x == y but is simpler. Answer

  6. Write a definition of function even(n), which returns true if n is even and returns false if n is odd. Assume that n has type int. Answer