位置:首页 > 高级语言 > C++教程 > C++ switch语句

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;
}
执行上面代码,得到以下结果 -
[codeinn@localhost cpp]$ g++ swith.cpp
[codeinn@localhost cpp]$ ./a.out
Enter a number to check grade:69
Not 10, 20 or 30
[codeinn@localhost cpp]$ ./a.out
Enter a number to check grade:89
Not 10, 20 or 30
[codeinn@localhost cpp]$ ./a.out
Enter a number to check grade:10
It is 10