I have just installed the Windows SDK v7.1 (MSVC 10.0) and running my code through (almost) full warning level (W3, default for qmake’s CONFIG += warn_on) and am surprised about warning C4800: 'type' : forcing value to bool 'true' or 'false' (performance warning)
In the following code, stream is an std::istream and token is a std::string.
// in some function returning bool
return (stream >> token) // triggers warning c4800:
// '(void *)': forcing value to bool 'true' or 'false' (performance warning)`
// somewhere else
if( stream >> token ) // does not trigger warning c4800
What is going on here? I don’t even get why the warning is triggered in the first place. I thought the first bit of code already returned a bool anyways.
I understand this is nitpicking and the warning shouldn’t even exist, but it’s the only one in my code between MSVC’s /W3 and gcc’s -Wall -pedantic, so I’d like to know 🙂
SMALL UPDATE: I understand that the warning is designed to let you know you’re assuming int->bool conversion, but 1) why would you even still use bool (== why would an typedef int mostly) and 2)if(2) not convert 2 to true or false, I thought that was the whole idea of a predicate, being true or false.
Streams have an implicit conversion operator that returns a
void*. (That’s a version of the safe bool idiom. It’s done this way because there is less contexts in whichvoid*compiles thanbool, so there’s less contexts in which the implicit conversion could kick in unwanted.)[1]Streams’
operator>>()returns a reference to its left operand – the stream. That’s so you can chain input operations:strm >> value1 >> value2is executed as((strm >> value1) >> value2).Now, when you say
if( strm >> value ),strm >> valueis executed and a stream returned. In order to put that into anifstatement, the implicit conversion intovoid*is performed, and that pointer is then checked for beingNULLor not.That’s no different from
if(ptr), theifstatement implicit converts its condition tobool, but compilers would never warn about that, because the condition not being aboolis so common.With the
return, this is different. If you want to return a certain type, usually the expression you return should be of that type. VC’s warning is quite annoying and for me in 99 out of 100 times it was superfluous. But the remaining 1% (never a performance concern, BTW; I think that is silly about the warning) made me glad the warning is there.The workaround for this warning is to
where
<expression>is whatever you think should be considered a boolean value.[1] ISTR Stroustrup writing somewhere that an
operator bool()would silently compile if you messed up the operators:ostrm >> 5;(note the>>instead of<<) would compile fine, but silently do the wrong thing. (It converts the boolean to an integer and right-shifts that 5 times, then discard the value.)