Why Use !! When Converting Int to Bool

Better way to convert an int to a boolean

I assume 0 means false (which is the case in a lot of programming languages). That means true is not 0 (some languages use -1 some others use 1; doesn't hurt to be compatible to either). So assuming by "better" you mean less typing, you can just write:

bool boolValue = intValue != 0;

Why use !! when converting int to bool?

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.

Casting int to bool in C/C++

0 values of basic types (1)(2)map to false.

Other values map to true.

This convention was established in original C, via its flow control statements; C didn't have a boolean type at the time.


It's a common error to assume that as function return values, false indicates failure. But in particular from main it's false that indicates success. I've seen this done wrong many times, including in the Windows starter code for the D language (when you have folks like Walter Bright and Andrei Alexandrescu getting it wrong, then it's just dang easy to get wrong), hence this heads-up beware beware.


There's no need to cast to bool for built-in types because that conversion is implicit. However, Visual C++ (Microsoft's C++ compiler) has a tendency to issue a performance warning (!) for this, a pure silly-warning. A cast doesn't suffice to shut it up, but a conversion via double negation, i.e. return !!x, works nicely. One can read !! as a “convert to bool” operator, much as --> can be read as “goes to”. For those who are deeply into readability of operator notation. ;-)



1) C++14 §4.12/1 “A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. For direct-initialization (8.5), a prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.”

2) C99 and C11 §6.3.1.2/1 “When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.”

Converting Int to Bool

No, there is and has never been an explicit built in option for conversion of Int to Bool, see the language reference for Bool for details.

There exists, still, however, an initializer by NSNumber. The difference is that implicit bridging between Swift numeric type and NSNumber has been removed in Swift 3 (which previously allowed what seemed to be explicit Bool by Int initialization). You could still access this by NSNumber initializer by explicitly performing the conversion from Int to NSNumber:

let number = 1
let result = Bool(number as NSNumber)

print(result) // true

As @Hamish writes in his comment below: if we leave the subject of initializers and just focus on the end result (instantiating a Bool instance given the value of an Int instance) we can simply make use of the != operator for Int values (specifically, the operator with signature func !=(lhs: Int, rhs: Int) -> Bool), a generalization easily achievable using the != operator approach:

let number = -1
let result = number != 0

print(result) // true

Much like you yourself as well as @JAL describes in his answer, you could construct your own Bool by Int initializer, but you might as well consider generalizing this for any type conforming to the Integer protocol:

extension Bool {
init<T: Integer>(_ num: T) {
self.init(num != 0)
}
}

/* example usage */
let num1: Int8 = -1
let num2: Int = 3
let num3: UInt64 = 0
// ....
let result1 = Bool(num1) // true
let result2 = Bool(num2) // true
let result3 = Bool(num3) // false

Why does casting an int to a bool give a warning?

Just because the conversion a => b is implicit doesn’t say anything about the viability of the reverse, b => a.

In your case, you shouldn’t cast at all. Just do the obvious thing: compare:

bool result = int_value != 0;

This is the only logically correct way of converting an int to bool and it makes the code much more readable (because it makes the assumptions explicit).

The same applies for the reverse, by the way. Converting implicitly from bool to int is just lazy. Make the mapping explicit:

int result = condition ? 1 : 0;

Cannot implictly convert type int to bool

i % 2 is of type int, not bool, C# cannot automatically make the conversion, so simply try:

i % 2 != 0

bool to int conversion

int x = 4<5;

Completely portable. Standard conformant. bool to int conversion is implicit!

§4.7/4 from the C++ 11 or 14 Standard, §7.8/4 from the C++ 17 Standard, §7.3.9/2 from the 20 Standard says (Integral Conversion)

If the source type is bool, the value false is converted to zero and
the value true is converted to one.


As for C, as far as I know there is no bool in C. (before 1999) So bool to int conversion is relevant in C++ only. In C, 4<5 evaluates to int value, in this case the value is 1, 4>5 would evaluate to 0.

EDIT: Jens in the comment said, C99 has _Bool type. bool is a macro defined in stdbool.h header file. true and false are also macro defined in stdbool.h.

§7.16 from C99 says,

The macro bool expands to _Bool.

[..] true which expands to the integer constant 1, false
which expands to the integer constant 0,[..]

I am not able to convert int to boolean in Java in the following code

Not every type can be cast to another. int to boolean is one of those that is not permitted in Java. The Java Language Specification explains what is and what isn't possible.

What is the performance implication of converting to bool in C++?

I was puzzled by this behaviour, until I found this link:

http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=99633

Apparently, coming from the Microsoft Developer who "owns" this warning:

This warning is surprisingly
helpful, and found a bug in my code
just yesterday. I think Martin is
taking "performance warning" out of
context.

It's not about the generated code,
it's about whether or not the
programmer has signalled an intent to
change a value from int to bool
.
There is a penalty for that, and the
user has the choice to use "int"
instead of "bool" consistently (or
more likely vice versa) to avoid the
"boolifying" codegen. [...]

It is an old warning, and may have
outlived its purpose, but it's
behaving as designed here.

So it seems to me the warning is more about style and avoiding some mistakes than anything else.

Hope this will answer your question...

:-p

How to convert integer to boolean in C#

This will solve your error (having a bool return type instead of the int) and will make your code shorter:

public bool IsUserInRole(IsUserInRole userInRole)
{
return _userRepository.CheckIfUserIsInRole(userInRole) == 1;
}


Related Topics



Leave a reply



Submit