为什么C ++要求在switch语句中中断? [英] Why does C++ require breaks in switch statements?
问题描述
在用C ++编写 switch 语句时,似乎有必要在每个 case 之后添加一个 break .否则,代码将继续遇到下一种情况.
When writing switch statements in C++, it seems necessary to include a break after every case. Otherwise, the code will continue to run into the next case.
例如:
int x = 1;
switch (x)
{
case 0:
std::cout << "x is 0." << std::endl;
case 1:
std::cout << "x is 1." << std::endl;
case 2:
std::cout << "x is 2." << std::endl;
default:
std::cout << "x is neither 0, 1 nor 2." << std::endl;
}
会返回:
>> x is 1.
>> x is 2.
但是:
int x = 1;
switch (x)
{
case 0:
std::cout << "x is 0." << std::endl;
break;
case 1:
std::cout << "x is 1." << std::endl;
break;
case 2:
std::cout << "x is 2." << std::endl;
break;
default:
std::cout << "x is neither 0, 1 nor 2." << std::endl;
break;
}
会返回:
>> x is 1.
我的问题是:如果必须在每个 case 中都包含 break ,那么为什么C ++要求完全将其明确编写?为什么在C ++中默认情况下,为什么不只是在每个 case 之后 break switch 语句呢?有没有可能实际上不希望这种行为的示例?
My question is: If it is necessary to include the break for every case, then why does C++ require it to be explicitly written at all? Why not just break the switch statement after every case by default in C++? Are there any examples when this behaviour may not in fact be desired?
推荐答案
这是为了解决所有问题":
This is for the favour of "falling throught" cases:
switch (x)
{
case 0:
case 1:
std::cout << "x is 0 or 1." << std::endl;
break;
}
在此示例中,如果x为0或1,则执行case语句.
In this example, the case statement is executed if x is either 0 or 1.
这篇关于为什么C ++要求在switch语句中中断?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!