switch statement

  1. 流程圖
    \begin{tikzpicture}[node distance=1.3cm]\setlength \baselineskip{1ex}
\node [input,name=input] {};
......
  2. 語法:break 可有可無,有沒有 break 有何差別?
    switch(expression){
        case constant-expression  :
           statement(s);
           break; /* optional */
        case constant-expression  :
           statement(s);
           break; /* optional */
      
        /* you can have any number of case statements */
        default : /* Optional */
           statement(s);
    }
    
  3. 範例
    [dywang@deyu zzz]$ vim sw1.c
    [dywang@deyu zzz]$ cat sw1.c
    #include <stdio.h>
    
    int main() {
    	char grade;
    	printf("Enter a char: ");
    	scanf("%c", &grade);
    
    	switch(grade) {
    	case 'A' :
    		printf("Excellent!\n" );
    		break;
    	case 'B' :
    	case 'C' :
    		printf("Well done\n" );
    		break;
    	case 'D' :
    		printf("You passed\n" );
    		break;
    	case 'F' :
    		printf("Better try again\n" );
    		break;
    	default :
    		printf("Invalid grade\n" );
    	}
    	printf("Your grade is  %c\n", grade );
    }
    
  4. 編譯成功
    [dywang@deyu zzz]$ gcc -o sw1 sw1.c
    
  5. 執行結果一
    [dywang@deyu zzz]$ ./sw1
    Enter a char: A
    Excellent!
    Your grade is  A
    
  6. 執行結果一:輸入 A, C, D, F 都依判斷結果輸出。
    [dywang@deyu zzz]$ ./sw1
    Enter a char: C
    Well done
    Your grade is  C
    [dywang@deyu zzz]$ ./sw1
    Enter a char: D
    You passed
    Your grade is  D
    [dywang@deyu zzz]$ ./sw1
    Enter a char: F
    Better try again
    Your grade is  F
    
  7. 執行結果二:輸入 B 時,沒有任何的執行敘述,而且沒有 break,所以不會跳出 case 判斷式,網續往下執行輸出 "well done"。
    [dywang@deyu zzz]$ ./sw1
    Enter a char: B
    Well done
    Your grade is  B
    
  8. 執行結果三:輸入 E 及數字 43,都屬於最後的其他選項,輸出 "Invalid grade"。
    [dywang@deyu zzz]$ ./sw1
    Enter a char: E
    Invalid grade
    Your grade is  E
    [dywang@deyu zzz]$ ./sw1
    Enter a char: 43
    Invalid grade
    Your grade is  4