In C, does (x==y==z) behave as I'd expect?

僤鯓⒐⒋嵵緔 提交于 2019-12-01 00:01:00

问题


Can I compare three variables like the following, instead of doing if((x==y)&&(y==z)&&(z=x))? [The if statement should execute if all three variables have the same value. These are booleans.]

if(debounceATnow == debounceATlast == debounceATlastlast)
{
 debounceANew = debounceATnow;
}
else
{
 debounceANew = debounceAOld;
}

回答1:


No, it does not.

x == y is converted to int, yields 0 or 1, and the result is compared to z. So x==y==z will yield true if and only if (x is equal to y and z is 1) or (x is not equal to y and z is 0)

What you want to do is

if(x == y && x == z)



回答2:


No. The equality check associates from the left and the logical result is compared as a number, so that the expression 2 == 2 == 1 parses as (2 == 2) == 1, which in turn gives 1 == 1 and results in 1, which is probably not what you want.




回答3:


You can actually type something like this:

int main()
{
        const int first = 27,
                  second = first,
                  third = second,
                  fourth = third;
        if (!((first & second & third) ^ fourth))
            return 1;
        return 0;
}


来源:https://stackoverflow.com/questions/4378131/in-c-does-x-y-z-behave-as-id-expect

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