8

Possible Duplicate:
Double Negation in C++ code

As far as I know, no C/C++ books tutorials or manuals mention this technique. Maybe because it's just a tiny little thing, not worth mentioning.

I use it because C/C++ mixes bool type with int, long, pointer, double etc...together. It's very common to need to convert a non-bool to bool. It's not safe to use (bool)value to do that, so I use !! to do it.

Example:

bool bValue = !!otherValue;
Community
  • 1
  • 1
Rob Lao
  • 1,526
  • 4
  • 14
  • 38

3 Answers3

19

It's fine, any C or C++ programmer should recognize it, but I would prefer something more explicit like

(x != 0)
Ed S.
  • 122,712
  • 22
  • 185
  • 265
10

I think !! is quite clear in comparison to some of the other choices such as :

if (foo)
  bar = 1;
else
  bar = 0;

or bar = foo ? 1 : 0;

Since !! does exactly one thing, I find it very unambiguous.

sarnold
  • 102,305
  • 22
  • 181
  • 238
5

In this exact case:

bool bValue = !!otherValue;

you don't need to write !!. It will work fine without them:

bool bValue = otherValue;

I think in most cases implicit casting will be nice.

Pavel Strakhov
  • 39,123
  • 5
  • 88
  • 127
  • Implicit casting (when it can cause data truncation) causes compiler warnings, explicit casting (via operators in this case) does not. – ildjarn May 02 '12 at 00:44