switch / case 語法敘述
switch...case
類似於 if
,可以控制程式的運作,令程式在不同的情況下執行不同的程式碼。switch...case
可將傳入 switch
的數值與各 case
的常數數值做比較,當我們找到哪一個 case
的常數數值與傳入 switch
的數值相同時,則執行此 case
的程式碼區塊。
關鍵字 break
可以脫離 switch...case
的區塊,break
通常用於任一 case
程式碼區塊的最尾端。如果沒有使用 break
,則程式會持續的執行直到遇見 break
或 switch
區塊的最尾端。
範例
switch (var) { case 1: // 如果var值等於1則執行這段 break; case 2: // 如果var值等於2則執行這段 break; default: // 如果沒有符合的 case 則執行 default // default 區塊可省略 }
語法
switch (var) {
case label:
// statements
break;
case label:
// statements
break;
default:
// statements
}
參數
var
: 與 label
比較的變數值
label
: 與 var
比較的數值
See also
- if…else
本頁由熱血青年 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.