2010-12-07 25 views
11

我可以比較以下三個變量,而不是做if((x==y)&&(y==z)&&(z=x))? [如果所有三個變量具有相同的值,則應執行if語句。這些都是布爾]在C中,(x == y == z)的行爲如我所料嗎?

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

-1不花錢30秒編寫一個測試程序,找出。 – 2010-12-07 15:10:20

+4

./shrug 我對理解爲什麼不起作用更感興趣。感謝大家。 – Isaac 2010-12-07 15:24:15

回答

33

不,不。

x == y轉換爲int,收率01,並且將結果進行比較,z。所以,當且僅當(x is equal to y and z is 1) or (x is not equal to y and z is 0)

你想要做什麼是

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

號從左邊和邏輯結果的平等檢查聯營爲數字相比,x==y==z將產生真正的,這樣的表達2 == 2 == 1解析爲(2 == 2) == 1,反過來給1 == 1和結果在1,這可能不是你想要的。

1

實際上,你可以鍵入像這樣:

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