Sams Teach Yourself C++ in 21 Days

(singke) #1
Creating Expressions and Statements 79

4


The Nature of Truth ..............................................................................................


Every expression can be evaluated for its truth or falsity. Expressions that evaluate math-
ematically to zero return false; all others return true.
In previous versions of C++, all truth and falsity was represented by integers, but the
ANSI standard introduced the type bool. A boolcan only have one of two values:false
or true.

Many compilers previously offered a booltype, which was represented inter-
nally as a long intand, thus, had a size of four bytes. Now, ANSI-compliant
compilers often provide a one-byte bool.

NOTE


Evaluating with the Relational Operators ........................................................


The relational operators are used to compare two numbers to determine whether they are
equal or if one is greater or less than the other. Every relational statement evaluates to
either trueor false. The relational operators are presented later, in Table 4.1.

All relational operators return a value of type bool, that is either trueor
false. In previous versions of C++, these operators returned either 0 for
false or a nonzero value (usually 1) for true.

NOTE


If the integer variable myAgehas the value 45 , and the integer variable yourAgehas the
value 50 , you can determine whether they are equal by using the relational “equals”
operator (==):
myAge == yourAge; // is the value in myAge the same as in yourAge?
This expression evaluates to falsebecause the variables are not equal. You can check to
see if myAgeis less than yourAgeusing the expression,
myAge < yourAge; // is myAge less than yourAge?
which evaluates to truebecause 45 is less than 50.

Many novice C++ programmers confuse the assignment operator (=) with
the equals operator (==). This can create a nasty bug in your program.

CAUTION

Free download pdf