介绍C++switch函数的使用方法
时间: 2023-07-05 20:27:38 浏览: 156
C++中的switch语句可以根据一个表达式的值来执行不同的语句。其基本语法如下:
```
switch(expression) {
case constant-expression1:
// 执行语句块1
break;
case constant-expression2:
// 执行语句块2
break;
.
.
.
default:
// 执行语句块N
}
```
其中,expression为需要比较的表达式,case后面跟的是常量表达式,用来与表达式expression进行比较。如果表达式expression的值与某个case后面的常量表达式相等,则执行该case后面的语句块。如果没有任何case的常量表达式与表达式expression的值相等,则执行default后面的语句块。
在执行语句块时,可以使用break语句来跳出switch语句,直接执行switch后面的语句。如果没有使用break语句,则会一直执行到遇到break或者switch语句结束为止。
以下是一个简单的示例:
```
#include <iostream>
using namespace std;
int main() {
int num = 2;
switch (num) {
case 1:
cout << "num is 1" << endl;
break;
case 2:
cout << "num is 2" << endl;
break;
case 3:
cout << "num is 3" << endl;
break;
default:
cout << "num is not 1, 2 or 3" << endl;
}
return 0;
}
```
输出结果为:num is 2
阅读全文
相关推荐















