解釋 C 語言中的巢狀 switch case
問題
使用巢狀 switch case 編寫一個 C 程式,根據使用者的 ID 檢查使用者輸入的密碼是否有效。
解決方案
以下是解決方案說明 −
在 C 語言中,我們可以編寫巢狀在外部 switch 中的內部 switch。
內部和外部 switch 的 case 值可以是相同的值。
規則
- 一個表示式執行得出結果。
- case 標籤必須使用常量和唯一值。
- case 標籤必須以冒號 ( : ) 結尾。
- 每個 case 中必須包含 break 關鍵字。
- 只能有一個 default 標籤。
- 我們可以編寫多個巢狀 switch 語句。
示例
以下是使用巢狀 switch case 根據使用者 ID 檢查使用者輸入的密碼是否有效的 C 程式 −
#include <stdio.h> int main(){ int userid; int pwd; printf("enter userid:
"); scanf("%d",&userid); switch (userid){ case 1234: printf("enter password:
"); scanf("%d", & pwd); switch (pwd){ case 0000: printf("Tutorials Point
"); break; default: printf("incorrect password"); break; } break; default: printf("incorrect userid"); break; } }
輸出
您將看到以下輸出 −
Run 1:enter userid: 1234 enter password: 0000 Tutorials Point Run 2: enter userid: 1234 enter password: 234 incorrect password
廣告