Arduino - if…else if …else 語句



if 語句後面可以跟一個可選的 else if...else 語句,這在使用單個 if...else if 語句測試各種條件時非常有用。

使用if...else if…else 語句時,請記住 -

  • 一個if 可以有零個或一個 else 語句,並且它必須位於任何 else if 之後。

  • 一個if 可以有零個到多個 else if 語句,並且它們必須位於 else 之前。

  • 一旦一個else if 成功,就不會測試任何剩餘的 else if 或 else 語句。

if … else if …else 語句語法

if (expression_1) {
   Block of statements;
}

else if(expression_2) {
   Block of statements;
}
.
.
.

else {
   Block of statements;
}

if … else if … else 語句執行順序

If Else If Else Statement

示例

/* Global variable definition */
int A = 5 ;
int B = 9 ;
int c = 15;

Void setup () {

}

Void loop () {
   /* check the boolean condition */
   if (A > B) /* if condition is true then execute the following statement*/ {
      A++;
   }
   /* check the boolean condition */
   else if ((A == B )||( B < c) ) /* if condition is true then 
      execute the following statement*/ {
      C = B* A;
   }else
      c++;
}
arduino_control_statements.htm
廣告