Section 4 - Relational Expressions

3B.4.1 Boolean Type

Before we continue, let me introduce a new primitive data type: bool. Bool stands for Boolean, which means logical.  Bool objects can have only one of two values: true or false. Those two words, or bool literals, are reserved words and are the constants of the bool type.

bool x;

x = true;

This is the bool version of declaring a variable and then setting it to one of the two legal constants.  

In C++ the value true is equivalent to 1, and false is equivalent to 0.  If you were to print out a bool value, you would not see "true" or "false" but 0 and 1.  This is one place where C++ differs from all other programming languages.

3B.4.2 The Relational

In a statement like

if (price < .12)

it is pretty clear what we are asking about price: is it less than .12?. The complete vocabulary for this type of expression is:

is equal to is less than is greater than is less than or equal to is greater than or equal to is not equal to
== < > <= >= !=

These are questions, not commands. We say

x+y <= 100

and we are asking is x+y less than or equal to 100?. If the answer is yes, then the entire expression is replaced with the bool value, true.  If not, the expression is replaced with the bool value false.   (Actually, as I said earlier, it actually replaced by the value 1 or 0 for true and false, respectively).

if (a == b)
a--;

means, if a equals b, then decrement (subtract 1 from) a. (a++ is shorthand for a = a+1 and a-- is shorthand for a = a-1. These are called the increment and decrement operators. While I'm on the subject, a += 4 is shorthand for a = a+4, a *= 5 means a = a*5, a /= 2 means a = a/2, and so on.)

The full description of the short expression:

if (a == b)
a--;

is as follows:

  1. a == b is tested. If a is equal to b, then this expression is replaced by the bool constant true (which is really the number 1 in C++). If not, it is replaced by false, which is the number 0 in C++).
  2. The expression now becomes either:
    if (true)
    a--;
    
    or
    if (false)
    a--;
    
    In the former case, the statement a-- is executed. In the latter, it is not executed.

Because bool values true and false are really int values, you can actually place an int inside the if() expression.  This is a little confusing.  After all, what does if (9) or if (a+b) mean?  Well in C++ if the value is non-zero it is considered true.  So if(9) is always considered a true test.  if(a+b) means if a+b is non-zero, then do what's in the if block.