I reading this code, and have this line
switch (!!up + !!left) {
what is !! operator ? two logical NOT ?
I reading this code, and have this line
switch (!!up + !!left) {
what is !! operator ? two logical NOT ?
yes, it's two nots.
!!a is 1 if a is non-zero and 0 if a is 0
You can think of !! as clamping, as it were, to {0,1}. I personally find the usage a bad attempt to appear fancy.
You can imagine it like this:
!(!(a))
If you do it step by step, this make sense
result = !42; //Result = 0
result = !(!42) //Result = 1 because !0 = 1
This will return 1 with any number (-42, 4.2f, etc.) but only with 0, this will happens
result = !0; //Result = 1
result = !(!0) //result = 0
!! is a more-portable (pre-C99) alternative to (_Bool).
You're right. It's two nots. To see why one would do this, try this code:
#include <stdio.h>
int foo(const int a)
{
return !!a;
}
int main()
{
const int b = foo(7);
printf(
"The boolean value is %d, "
"where 1 means true and 0 means false.\n",
b
);
return 0;
}
It outputs The boolean value is 1, where 1 means true and 0 means false. If you drop the !!, though, it outputs The boolean value is 7, where 1 means true and 0 means false.