布林运算子

這些布林運算子可以被應用在 if 條件語句中。

&& (邏輯上的 and)

若兩運算元皆為真,則判斷結果為真,如:

if (digitalRead(2) == HIGH  && digitalRead(3) == HIGH) { // 檢查兩個開關是否都被按下
  // ...
} 

若兩輸入皆為 HIGH,則為真。

|| (邏輯上的 or)

若其中一個運算元為真,則為真。如:

if (x > 0 || y > 0) {
  // ...
} 

若 x 或 y 大於 0,則為真。

! (not)

若運算元為假,則為真。如:

if (!x) { 
  // ...
} 

若 x 為假(即 x 等於 0),則為真。

警告

寫程式過程中, 你應該要避免誤用 AND 布林運算子「&&」和 AND 位元運算子「&」。它們是完全不同的東西。

同樣地,勿將 OR 布林運算子「||」和 OR 位元運算子「|」混淆。

NOT位元運算子「~」和NOT布林運算子「!」也大不相同,你須確認需要何種運算,避免誤用。

範例


if (a >= 10 && a <= 20){} // 如果 a 介於 10 到 20 則條件為真

See also

& (bitwise AND)
| (bitwise OR)
~ (bitwise NOT)
if


語法參考主頁面

本頁由熱血青年 LBU 譯自英文版。

The text of the 86Duino reference is a modification of the Arduino reference, and is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the reference are released into the public domain.