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;
}

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

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

上一篇: C++ if/else語句 下一篇: C++ for迴圈