Why use !! when converting int to bool?
Solution 1:
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.
Solution 2:
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
.