C Switch
Switch 語句
與編寫一堆 if..else
語句相比,您可以使用 switch
語句。
The switch
statement selects one of many code blocks to be executed
語法
switch (expression) {
case x
// 程式碼塊
break;
case y
// 程式碼塊
break;
default
// 程式碼塊
}
工作原理如下
- switch 表示式只計算一次
- 表示式的值與每個 case 的值進行比較
- 如果匹配成功,則執行關聯的程式碼塊
- The
break
statement breaks out of the switch block and stops the execution - The
default
statement is optional, and specifies some code to run if there is no case match
下面的示例使用工作日數字來計算工作日名稱。
示例
int day = 4;
switch (day) {
case 1
printf("Monday");
break;
case 2
printf("Tuesday");
break;
case 3
printf("Wednesday");
break;
case 4
printf("Thursday");
break;
case 5
printf("Friday");
break;
case 6
printf("Saturday");
break;
case 7
printf("Sunday");
break;
}
// 輸出“星期四”(第 4 天)
自己動手試一試 »
break 關鍵字
When C reaches a break
keyword, it breaks out of the switch block.
這將停止塊內更多程式碼和 case 測試的執行。
當找到匹配項並完成任務時,就該中斷了。無需再進行測試。
break 可以節省大量執行時間,因為它“忽略”了 switch 塊中所有其餘程式碼的執行。
default 關鍵字
default
關鍵字指定了在沒有 case 匹配時執行的一些程式碼。
示例
int day = 4;
switch (day) {
case 6
printf("Today is Saturday");
break;
case 7
printf("Today is Sunday");
break;
default
printf("Looking forward to the Weekend");
}
// 輸出 "Looking forward to the Weekend"
自己動手試一試 »
Note: The default keyword must be used as the last statement in the switch, and it does not need a break.