开发者

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

开发者 https://www.devze.com 2023-03-21 12:43 出处:网络
This question already has answers here:开发者_JS百科 Closed 11 years ago. Possible Duplicate: Double Negation in C++ code.
This question already has answers here: 开发者_JS百科 Closed 11 years ago.

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.


It's converting BOOL (define for int) to c++ bool. BOOL is a define that in some cases for true can contain different integer values. So for example BOOL a = (BOOL)1; and BOOL b =(BOOL)2; both pass check for true. But if you'll try to compare you'll find that a not equals b. But after conversion !!a equals !!b.

(bool)notABoo - is not akin, because you'll convert type of variable byte still'll have different values. !! converts not only type but in some cases values too.

0

精彩评论

暂无评论...
验证码 换一张
取 消