Why use !! when converting int to bool?
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
.
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.
Because !integerValue means integerValue == 0 and !!integerValue thus means integerValue != 0, a valid expression returning a bool. The latter is a cast with information loss.
It is used because the C language (and some pre-standard C++ compilers too) didn't have the bool
type, just int
. So the int
s were used to represent logical values: 0
was supposed to mean false
, and everything else was true
. The !
operator was returning 1
from 0
and 0
from everything else. Double !
was used to invert those, and it was there to make sure that the value is just 0
or 1
depending on its logical value.
In C++, since introducing a proper bool
type, there's no need to do that anymore. But you cannot just update all legacy sources, and you shouldn't have to, due to backward compatibility of C with C++ (most of the time). But many people still do it, from the same reason: to remain their code backward-compatible with old compilers which still don't understand bool
s.
And this is the only real answer. Other answers are misleading.