Alex Rivera | Logout

Why use !! when converting int to bool?

Asked 2009-08-21T06:36:12.007
77

What can be a reason for converting an integer to a boolean in this way?

bool booleanValue = !!integerValue;

instead of just

bool booleanValue = integerValue;

All I know is that in VC++7 the latter will cause C4800 warning and the former will not. Is there any other difference between the two?

Edit
Report

1 Answer

4

!! is an idiomatic way to convert to bool, and it works to shut up the Visual C++ compiler's sillywarning about alleged inefficiency of such conversion.

I see by the other answers and comments that many people are not familiar with this idiom's usefulness in Windows programming. Which means they haven't done any serious Windows programming. And assume blindly that what they have encountered is representative (it is not).

#include <iostream>
using namespace std;

int main( int argc, char* argv[] )
{
    bool const b = static_cast< bool >( argc );
    (void) argv;
    (void) b;
}
> [d:\dev\test]
> cl foo.cpp
foo.cpp
foo.cpp(6) : warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning)

[d:\dev\test]
> _

And at least one person thinks that if an utter novice does not recognize its meaning, then it's ungood. Well that's stupid. There's a lot that utter novices don't recognize or understand. Writing one's code so that it will be understood by any utter novice is not something for professionals. Not even for students. Starting on the path of excluding operators and operator combinations that utter novices don't recognize... Well I don't have the words to give that approach an appropriate description, sorry.

answered 2011-11-19T07:56:55.123

Your Answer