Possible Duplicate:
Double Negation in C++ code.
I am working with production code where I have run across statements like this a few times:
Class.func(!!notABool);
The first couple of times I dismissed it as a programmer quirk
(maybe to emphasize that it is a conditional statement rather than a number being passed into func?) but I have run across several statements that use the above and now I am wondering whether it actually makes a difference or not. In most cases notABool
is a number(int, float, double... I have seen all 3) My initial guess was that it is akin to typing:
Class.func((bool)notABool);
but I am not entirely sure?
Yes, functionally it is exactly the same as doing (bool) notABool
.
By definition, in C++ language the operand of !
is implicitly converted to bool
type, so !!notABool
is really the same as !! (bool) notABool
, i.e. the same as just (bool) notABool
.
In C language the !!
was a popular trick to "normalize" a non-1/0 value to 1/0 form. In C++ you can just do (bool) notABool
. Or you can still use !!notABool
if you so desire.
For primitive types, yes, it's essentially equivalent to:
!(notABool != 0)
which in turn is equivalent to:
(bool)notABool
For non-primitive types, it will be a compiler error, unless you've overloaded operator!
, in which case, it might do anything.
It's a legacy idiom from C, where it meant "normalize to 0 or 1". I don't think there's a reason to use it in C++ other than habit.
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