Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 (e.g., 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.

like image 799
jwfearn Avatar asked Oct 15 '08 19:10

jwfearn


People also ask

Should I use bool or int?

If you choose a bool (boolean) type, it is clear there are only two acceptable values: true or false . If you use an int (integer) type, it is no longer clear that the intent of that variable can only be 1 or 0 or whatever values you chose to mean true and false .

Is bool the same as int?

Treating integers as boolean values C++ does not really have a boolean type; bool is the same as int. Whenever an integer value is tested to see whether it is true of false, 0 is considered to be false and all other integers are considered be true.

Where is bool defined in C?

bool exists in the current C - C99, but not in C89/90. In C99 the native type is actually called _Bool , while bool is a standard library macro defined in stdbool. h (which expectedly resolves to _Bool ). Objects of type _Bool hold either 0 or 1, while true and false are also macros from stdbool.

Can bool be used as int in C++?

Bool to int conversion in C++ Bool is a datatype in C++, and we can use true or false keyword for it. If we want to convert bool to int, we can use typecasting. Always true value will be 1, and false value will be 0.


2 Answers

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.

like image 196
fizzer Avatar answered Sep 22 '22 07:09

fizzer


Alternatively, you can do this: bool b = (t != 0)

like image 41
Dima Avatar answered Sep 22 '22 07:09

Dima