C++ – Why Bool Accepts Int, Char, and String Literals

c

Programming: Practices and Principles – Bjarne Stroustrup

Drill in Ch 5 – Errors

He wants us to correct the code:

boo c = "fool"<s;

On correcting boo to bool, this is a comparison, so that's fine. c will be assigned either true or false. But if I edit it to

bool c = "fool";

It also evaluates to true. Then I tried "", 'd', 235, and they all evaluate to true. Shouldn't there be a type error? Narrowing conversion? Something? (I tried {} for checking narrowing conversions.)

Best Answer

As can be found here, there is a conversion happening:

Prvalues of integral, floating-point, unscoped enumeration, pointer, and pointer-to-member types can be converted to prvalues of type bool.

The value zero (for integral, floating-point, and unscoped enumeration) and the null pointer and the null pointer-to-member values become false. All other values become true.