開關陳述式

出自維基百科,自由嘅百科全書
Jump to navigation Jump to search

開關陳述式switch statement)喺編程上係指會攞某個特定變數嘅數值同一柞預先講好咗嘅常數嘅數值比較,再選擇同個特定變數吻合嗰個常數,做嗰個常數後面掕住嗰柞碼。喺多數程式語言入面,段碼仲會掕住一個 ELSE,表示「如果嗰個變數唔吻合任何一個常數嘅值,要行嘅碼」。原則上,開關陳述式係不必要嘅,因為一個開關陳述式可以寫做一個有大量 ELSE IF 嵌套在內嘅條件陳述式,但一般認為,開關陳述式喺要應對好多個個案嗰陣會清潔簡潔啲,而當個案數量多起上嚟,可以用尋找表(lookup table)嘅技術[1]

Pascal: Ada: C: Shell script: Lisp:
case someChar of
  'a': actionOnA;
  'x': actionOnX;
  'y','z':actionOnYandZ;
  else actionOnNoMatch;
end;
case someChar is
  when 'a' => actionOnA;
  when 'x' => actionOnX;
  when 'y' | 'z' => actionOnYandZ;
  when others => actionOnNoMatch;
end;
switch (someChar) {
  case 'a': actionOnA; break;
  case 'x': actionOnX; break;
  case 'y':
  case 'z': actionOnYandZ; break;
  default: actionOnNoMatch;
}
case $someChar in 
   a)    actionOnA ;;
   x)    actionOnX ;;
   [yz]) actionOnYandZ ;;
   *)    actionOnNoMatch  ;;
esac
(case someChar
  ((#\a)     actionOnA)
  ((#\x)     actionOnX)
  ((#\y #\z) actionOnYandZ)
  (else      actionOnNoMatch))

[編輯]

  1. switch vs if else. GeeksforGeeks.