Sometimes, I saw the following code:
if ( !!on_debugging )
which is the same as
if ( on_debugging )
I don't understand why these two !s are used. Is there any kind of difference?
Sometimes, I saw the following code:
if ( !!on_debugging )
which is the same as
if ( on_debugging )
I don't understand why these two !s are used. Is there any kind of difference?
!!a
is almost equivalent to a
. It converts it to a boolean value.
Usually this does not make a difference, but sometimes it does.
#include <iostream>
int a(int x) {
return 1;
}
int a(bool x) {
return 2;
}
int main() {
std::cout << a(0) << std::endl; //prints 1
std::cout << a(!!0) << std::endl; //prints 2
std::cout << -1 << std::endl; //prints -1
std::cout << !!-1 << std::endl; //prints 1
}
In your case, there is no difference, unless there is overloading. (But even if there is overloading, I hope there is no difference.)
(FYI, this is done even more commonly in Javascript because of its types, e.g. false != null
but false == !!null
. I include this comment because you tagged your question with C, C++, and Java, and Javascript shares similar syntax.)
If operator!
is not overloaded, the two statements are equivalent.
Where !!
might be useful is if you need to change a zero / non-zero value, or a nullptr
/ non-null pointer value into a 0/1 value in an integer expression.
For a (dubious) example, the following loop counts the number of non-zero elements in a vector:
for (size_t i = 0; i != v.size(); i++)
count += !!v[i];
You will sometimes see !!
in bit-level hacks as a result. But in the if
statement you show above? Unless operator!
is overloaded, that's not a useful operation.
Take this as an live example:
#include <stdio.h>
int main(void) {
int a = 5;
printf("%d\n", a);
printf("%d\n", !!a); // will print 1
return 0;
}
The main difference is a silly-warning from Visual C++.
Secondary (rare) differences include the case where you have an operator!
, and the case where the argument is used in a non-boolean context, e.g. arithmetic.
Double ! simplily means a unary NOT and another unary not. See it as (!(!on_debugging))
Yes, you are right, most of the time the results is the same as on_debugging
. I think this is for preciseness or strictness to use !!
because the !
operator only returns integer 0 or 1
, which corresponds to false
and true
. While the variable can be anything of int
and point
type.
For Java !!on_debugging
is the opposite of !!!on_debugging
.
You can negate stuff as often as you want, thus there is no difference between on_debugging
and !!on_debugging
.
Also see Java Language Specification for this operator:
The type of the operand expression of the unary ! operator must be boolean or Boolean, or a compile-time error occurs. (see JLS 15.15.6).