August 2001
Beginner
482 pages
10h 52m
English
In C++ zero is false, and any other value is true. Because expressions always have a value, many C++ programmers take advantage of this feature in their if statements. A statement such as
if (x) // if x is true (nonzero)
x = 0;
can be read as “If x has a nonzero value, set it to 0.” This is a bit of a cheat; it would be clearer if written
if (x != 0) // if x is nonzero
x = 0;
Both statements are legal, but the latter is clearer. It is good programming practice to reserve the former method for true tests of logic, rather than for testing for nonzero values.
These two statements are also equivalent:
if (!x) // if x is false (zero) if (x == 0) // if x is zero
The second statement, however, is somewhat easier ...
Read now
Unlock full access