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]$