cpp 专题
专题目录
您的位置:cpp > cpp 专题 > C++ switch语句
C++ switch语句
作者:--    发布时间:2019-11-20

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

执行上面代码,得到以下结果 -

[h3@localhost cpp]$ g++ swith.cpp
[h3@localhost cpp]$ ./a.out
enter a number to check grade:69
not 10, 20 or 30
[h3@localhost cpp]$ ./a.out
enter a number to check grade:89
not 10, 20 or 30
[h3@localhost cpp]$ ./a.out
enter a number to check grade:10
it is 10
[h3@localhost cpp]$

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册