stwich case贯穿
时间: 2023-10-17 19:35:15 浏览: 48
switch case 贯穿(fall-through)是指在 switch 语句中,如果没有在某个 case 语句中遇到 break 语句,程序会继续执行下一个 case 语句,而不是跳出 switch 语句。这样可以实现多个 case 语句共用相同的一段代码。
例如,考虑以下代码:
```cpp
int num = 2;
switch (num) {
case 1:
cout << "Number is 1" << endl;
break;
case 2:
cout << "Number is 2" << endl;
// Fall-through
case 3:
cout << "Number is 3" << endl;
break;
default:
cout << "Number is neither 1, 2, nor 3" << endl;
break;
}
```
在上述代码中,由于 `num` 的值为 2,所以会执行 `case 2` 中的代码,并且由于没有遇到 break 语句,程序会继续执行下一个 case 语句,即 `case 3` 中的代码也会被执行。因此,上述代码的输出将是:
```
Number is 2
Number is 3
```
需要注意的是,fall-through 在某些情况下可能是有用的,但在其他情况下可能会导致逻辑错误。因此,在使用 switch case 语句时,需要仔细考虑是否需要使用 fall-through,并确保程序的逻辑正确性。