Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using '!!' in C/C++ good practice and is it common? [duplicate]

Tags:

c++

c

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;
like image 784
Rob L Avatar asked May 02 '12 00:05

Rob L


3 Answers

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

(x != 0)
like image 134
Ed S. Avatar answered Nov 04 '22 08:11

Ed S.


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.

like image 10
sarnold Avatar answered Nov 04 '22 07:11

sarnold


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.

like image 5
Pavel Strakhov Avatar answered Nov 04 '22 08:11

Pavel Strakhov