简体   繁体   中英

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

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;
}

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 == 2 == 1解析为(2 == 2) == 1 ,这反过来给出1 == 1结果为1 ,这可能不是你想要的。

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM