Double Negation in C++

Brian Gianforcaro picture Brian Gianforcaro · Oct 29, 2008 · Viewed 33.6k times · Source

I just came onto a project with a pretty huge code base.

I'm mostly dealing with C++ and a lot of the code they write uses double negation for their boolean logic.

 if (!!variable && (!!api.lookup("some-string"))) {
       do_some_stuff();
 }                                   

I know these guys are intelligent programmers, it's obvious they aren't doing this by accident.

I'm no seasoned C++ expert, my only guess at why they are doing this is that they want to make absolutely positive that the value being evaluated is the actual boolean representation. So they negate it, then negate that again to get it back to its actual boolean value.

Is this correct, or am I missing something?

Answer

Don Neufeld picture Don Neufeld · Oct 29, 2008

It's a trick to convert to bool.