O'Reilly logo

Sams Teach Yourself C++ in 24 Hours, Third Edition by Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

More About Truth and Falsehood

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required