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?
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#.
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.
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 .
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 .
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.
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 int
s. This is less of an issue now with "real" bool
s.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With