!! c operator, is a two NOT?

旧巷老猫 提交于 2019-11-26 03:44:38

问题


I reading this code, and have this line

 switch (!!up + !!left) {

what is !! operator ? two logical NOT ?


回答1:


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.




回答2:


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



回答3:


!! is a more-portable (pre-C99) alternative to (_Bool).




回答4:


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.



来源:https://stackoverflow.com/questions/10307281/c-operator-is-a-two-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!