Equality Tests and the bool Literals

If we want to test the truth value of an arithmetic or pointer object, the most direct way is to use the value as a condition:

if (val)  { /*  ...  */ } // true if val is any nonzero value
if (!val) { /*  ...  */ } // true if val is zero

In both conditions, the compiler converts val to bool. The first condition succeeds so long as val is nonzero; the second succeeds if val is zero.

We might think we could rewrite a test of this kind as

if (val == true) { /* ...   */ } // true only if val is equal to 1!

There are two problems with this approach. First, it is longer and less direct than the previous code (although admittedly when first learning C++ this kind of abbreviation can be perplexing). Much more importantly, when val is not a bool, this comparison does not work as expected.

If val is not a bool, then true is converted to the type of val before the == operator is applied. That is, when val is not a bool, it is as if we had written

if (val == 1) { /* ... */ }

As we’ve seen, when a bool is converted to another arithmetic type, false converts to 0 and true converts to 12.1.2, p. 35). If we really cared whether val was the specific value 1, we should write the condition to test that case directly.


Image Warning

It is usually a bad idea to use the boolean literals true and false as operands in a comparison. These literals should be used only to compare to an object of type bool.



Exercises Section 4.3

Exercise 4.8: Explain when operands are evaluated in the logical AND, logical OR, and equality operators.

Exercise 4.9: Explain the behavior of the condition in the following if:

const char *cp = "Hello World";
if (cp && *cp)

Exercise 4.10: Write the condition for a while loop that would read ints from the standard input and stop when the value read is equal to 42.

Exercise 4.11: Write an expression that tests four values, a, b, c, and d, and ensures that a is greater than b, which is greater than c, which is greater than d.

Exercise 4.12: Assuming i, j, and k are all ints, explain what i != j < k means.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.80.100