Narrowing to bool

As mentioned previously, pointers, integers, and floating point values can be implicitly converted to bool where a nonzero value converts to true and a zero value converts to false. This can result in a nasty bug that is difficult to notice:

    int x = 0;     if (x = 1) cout << "not zero" << endl;     else       cout << "is zero" << endl;

Here, the compiler sees the assignment expression x = 1, which is a bug; it should be the comparison x == 1. However, this is valid C++ because the value of the expression is 1 and the compiler, helpfully, converts this to a bool value of true. This code will compile without even a warning, and not only will it produce a result that is the opposite of what you expect (you'll see not zero printed on ...

Get Beginning C++ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.