Is !! a safe way to convert to bool in C++?
[This question is related to but not the same as this one.]
If I try to use values of certain types as boolean expressions, I get a warning. Rather than suppress the warning, I sometimes use the ternary operator ( ?:
) to convert to a bool. Using two not operators ( !!
) seems to do the same thing.
Here's what I mean:
typedef long T; // similar warning with void * or double
T t = 0;
bool b = t; // performance warning: forcing 'long' value to 'bool'
b = t ? true : false; // ok
b = !!t; // any different?
So, does the double-not technique really do the same thing? Is it any more or less safe than the ternary technique? Is this technique equally safe with non-integral types (eg, with void *
or double
for T
)?
I'm not asking if !!t
is good style. I am asking if it is semantically different than t ? true : false
t ? true : false
.
The argument of the ! operator and the first argument of the ternary operator are both implicitly converted to bool, so !! and ?: are IMO silly redundant decorations of the cast. I vote for
b = (t != 0);
No implicit conversions.
或者,你可以这样做: bool b = (t != 0)
Careful!
Those are very distinct concepts:
When bridging those concepts, it should be done explicitly. I like Dima's version best:
b = (t != 0);
That code clearly says: Compare two numbers and store the truth-value in a boolean.
链接地址: http://www.djcxy.com/p/73542.html上一篇: C和C ++中的联合的目的