Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the usage of "!!" (negating twice)? [duplicate]

Tags:

c++

c

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.

like image 725
Renan Greinert Avatar asked Jan 17 '12 18:01

Renan Greinert


3 Answers

!! 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.

like image 149
Carl Norum Avatar answered Nov 14 '22 05:11

Carl Norum


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.

like image 28
Luchian Grigore Avatar answered Nov 14 '22 05:11

Luchian Grigore


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

like image 1
Daniel Fischer Avatar answered Nov 14 '22 04:11

Daniel Fischer