執行下列 C 程式後,產生的輸出為何?
#include<stdio.h>
int main(){
int i;
for(i= 0; i < 3; i++){
switch(i){
case 0: break;
case 1: printf("one ");
case 2: printf("two ");
case 3: printf("three ");
}
printf("four ");
}
return 0;
}
Afour one four two four
Bfour one two three four two three four正確答案
Cone two three four two three four three four
Dfour one two three four two three four three four
此選項假設每個 case 都有 break,忽略了 case 1 與 case 2 缺少 break 造成的 fall-through 效果。
Bfour one two three four two three fourswitch fall-through✓ 正確
i=0 時 case 0 有 break 跳出 switch,印 four;i=1 時 case 1 無 break,fall-through 依序印 one two three,再印 four;i=2 時 case 2 無 break,fall-through 印 two three,再印 four。合併為 four one two three four two three four。
Cone two three four two three four three four✕ 錯誤
Dfour one two three four two three four three four✕ 錯誤