15

Possible Duplicate:
Double Negation in C++ code

Let's say:

bool var = !!true;

It will assign "true" to the variable. Seems useless, but I was looking at Visual Studio's definition of "assert", and it is:

#define assert(_Expression) (void)( (!!(_Expression)) || (_wassert(_CRT_WIDE(#_Expression), _CRT_WIDE(__FILE__), __LINE__), 0) )

Why does it negate the "_Expression" twice?

I wonder that they want to force the "!" operator to be called (in the case it is overloaded), but that doesn't seem to be a good reason.

Community
  • 1
  • 1
Renan Greinert
  • 3,376
  • 3
  • 19
  • 29
  • 1
    http://stackoverflow.com/questions/248693/double-negation-in-c-code – cnicutar Jan 17 '12 at 18:51
  • http://stackoverflow.com/questions/1310344/why-use-when-converting-int-to-bool – cnicutar Jan 17 '12 at 18:51
  • A common reason would be to get a `0` or `1` from an expression that may have some other true value. I don't think that applies here. – Ben Jackson Jan 17 '12 at 18:51
  • 1
    Something the duplicate doesn't mention, but was asked here: It's useless if you're converting to `bool`. But once upon a time we had to use integer types to store booleans in C, and this was a useful way to avoid values other than `1` or `0`. – Mike Seymour Jan 17 '12 at 18:56
  • 4
    Unfortunately this question is closed, although it's not an exact duplicate. The *real* reason the above code uses `!!expr` rather than `bool(expr)` is to [**avoid microsoft's own stupid warning C4800**](http://msdn.microsoft.com/en-us/library/b6801kcy.aspx). The `!=0` trick doesn't work in generic contexts. – Yakov Galka Jan 17 '12 at 19:09
  • I had this exact same question once I read the definition for assert in VS. Thanks! – Dan Oct 04 '13 at 17:45

3 Answers3

7

!! guarantees that the result will end up as a 1 or a 0, rather than just the value of _Expression or 0. In C, it's unlikely to matter, but in C++ I think it turns the result of the expression into a bool type, which might be useful in some cases. If you did have some API that required a literal 1 or 0 be passed to it, using !! would be a way to make it happen.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
4

It's possible that you might want an int variable that's either 1 or 0.

So you can't for example pass a 5, instead the double negation would turn that 5 into a 1.

Also, have a look at how TRUE is defined:

#ifndef TRUE
#define TRUE                1
#endif

Therefore, an expression like:

int x = 5;
if ( x == TRUE )
{
   //....
}

would not pass, whereas

if ( x )
{
   //....
}

would.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
1

Its use is to make sure the value is either 0 or 1. I think it's superfluous with C++'s bool type.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431