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.
!!
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.
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.
Its use is to make sure the value is either 0 or 1. I think it's superfluous with C++'s bool type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With