问题
What are some valid uses for negating twice in C? For example, something like:
if (!!my_cond) {
}
As I understand, the !!
will guarantee that the !!my_cond
will be 0 if my_cond
is false
and 1 otherwise. When would you ever need to use this?
回答1:
In the context that you are showing it, it is useless, since the value itself would evaluate to 0
or 1
.
It can be usefull in a context that would not do such a "Boolean" conversion, such as arithmetic or indexing
size_t zerovalues[2] = { 0, 0, };
for (size_t i = 0; i < N; ++i)
++zerovalues[!!A[i]];
At the end you'd have the number of values 0 of A
in zerovalues[0]
and the number of those that aren't in zerovalues[1]
回答2:
It can be used for turning something into a Boolean expression.
If foo = !!foo
it gives foo
1 if it's not a zero, and leave it at 0 if it already is.
Your question is already answered here : Confused by use of double logical not (!!) operator
回答3:
The double-negative can be used top convert logical expressions to 0 or 1 so that they can be compared to other logical expressions.
int x = 63;
printf("Output: %d %d %d\n", x, !x, !!x);
Output: 63 0 1
This allows some logical boolean comparisons that would otherwise fail.
回答4:
It's not a good use case, but it's not inconceivable that you could run up against interfacing with code which uses this anti-pattern:
if (x == TRUE) ...
More generally, if you're implementing an API that is documented as specifially returning 0
on failure and 1
on success, this is perhaps the simplest way to sanitise the final return value.
回答5:
I believe that this is used to tell the compiler to treat the variable being tested as a bool type
来源:https://stackoverflow.com/questions/21661294/when-to-use-the-double-logical-not-in-c