Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does double not (!!) used on a non-boolean variable do? [duplicate]

Tags:

c++

boolean

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?

like image 252
Samaursa Avatar asked Jul 20 '11 15:07

Samaursa


3 Answers

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.

like image 98
AnT Avatar answered Nov 14 '22 17:11

AnT


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.

like image 44
Oliver Charlesworth Avatar answered Nov 14 '22 16:11

Oliver Charlesworth


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.

like image 27
Rafał Dowgird Avatar answered Nov 14 '22 15:11

Rafał Dowgird