C++ switch語句


C++ switch語句從多個條件執行一個語句。 它就類似於在C++中的if-else-if語句。

switch語句的基本語法如下所示 -

switch(expression){      
    case value1:      
        //code to be executed;      
        break;    
    case value2:      
        //code to be executed;      
        break;    
    ......      

    default:       
        //code to be executed if all cases are not matched;      
        break;    
}

switch語句的執行流程如下圖所示 -

C++ Switch範例

#include <iostream>  
using namespace std;  
int main () {  
    int num;  
    cout<<"Enter a number to check grade:";    
    cin>>num;  
    switch (num)    
    {    
        case 10: cout<<"It is 10"<<endl; break;    
        case 20: cout<<"It is 20"<<endl; break;    
        case 30: cout<<"It is 30"<<endl; break;    
        default: cout<<"Not 10, 20 or 30"<<endl; break;    
    }
    return 0;
}

執行上面程式碼,得到以下結果 -

[yiibai@localhost cpp]$ g++ swith.cpp
[yiibai@localhost cpp]$ ./a.out
Enter a number to check grade:69
Not 10, 20 or 30
[yiibai@localhost cpp]$ ./a.out
Enter a number to check grade:89
Not 10, 20 or 30
[yiibai@localhost cpp]$ ./a.out
Enter a number to check grade:10
It is 10
[yiibai@localhost cpp]$