Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use !! when converting int to bool?

What can be a reason for converting an integer to a boolean in this way?

bool booleanValue = !!integerValue; 

instead of just

bool booleanValue = integerValue; 

All I know is that in VC++7 the latter will cause C4800 warning and the former will not. Is there any other difference between the two?

like image 832
sharptooth Avatar asked Aug 21 '09 06:08

sharptooth


People also ask

Can you convert an int to a bool?

Since both integer and boolean are base data types, we can convert an integer value to a boolean value using the Convert class. The Convert. ToBoolean() method converts an integer value to a boolean value in C#.

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.

How do you convert int to boolean in Python?

Integers and floating point numbers can be converted to the boolean data type using Python's bool() function. An int, float or complex number set to zero returns False . An integer, float or complex number set to any other number, positive or negative, returns True .

Is bool a value type?

bool is a value type, this means that it cannot be null , so the Nullable type basically allows you to wrap value types, and being able to assign null to them. bool? can contain three different values: true , false and null .


2 Answers

The problems with the "!!" idiom are that it's terse, hard to see, easy to mistake for a typo, easy to drop one of the "!'s", and so forth. I put it in the "look how cute we can be with C/C++" category.

Just write bool isNonZero = (integerValue != 0); ... be clear.

like image 156
user143506 Avatar answered Sep 22 '22 05:09

user143506


Historically, the !! idiom was used to ensure that your bool really contained one of the two values expected in a bool-like variable, because C and C++ didn't have a true bool type and we faked it with ints. This is less of an issue now with "real" bools.

But using !! is an efficient means of documenting (for both the compiler and any future people working in your code) that yes, you really did intend to cast that int to a bool.

like image 34
T.J. Crowder Avatar answered Sep 22 '22 05:09

T.J. Crowder