不区分交换机这样的工作? [英] Does case-switch work like this?
问题描述
我碰到$ C $今天C的情况下,开关件,是有点惊讶地看到它是如何worked.The code是
I came across a case-switch piece of code today and was a bit surprised to see how it worked.The code was
switch (blah)
{
case a:
break;
case b:
break;
case c:
case d:
case e:
{
code here
}
break;
default :
return;
}
要我在变量是c中的路径场景惊喜code在这里里面去了。我段同意存在的情况下开关的C部分的结束没有中断,但我将不得不想象的要经过默认instead.When你降落在一个案例胡说:行犯规检查它,如果你的当前值的具体情况相匹配的才把让你在特定的细分,否则有什么?有一个情况呢?
To my surprise in the scenario where variable was c the path went inside the "code here" segment .I agree there is no break at the end of the 'c' part of the case switch but i would have imagined it to go through default instead.When you land at a "case blah : " line doesnt it check if your current value matches the particular case and only then let you in the specific segment?Otherwise what's the point of having a case?
推荐答案
这就是所谓案例落空,是一个理想的行为。它可以让你分享案例之间code。
This is called case fall-through, and is a desirable behavior. It allows you to share code between cases.
如何使用的情况下落空行为的一个例子:
An example of how to use case fall-through behavior:
switch(blah)
{
case a:
function1();
case b:
function2();
case c:
function3();
break;
default:
break;
}
如果你输入的开关时,等等== A
,那么你将执行功能1()
,函数2()
和 function3()
。
If you enter the switch when blah == a
, then you will execute function1()
, function2()
, and function3()
.
如果你不希望有这种行为,可以通过包括退出它破
语句。
If you don't want to have this behavior, you can opt out of it by including break
statements.
switch(blah)
{
case a:
function1();
break;
case b:
function2();
break;
case c:
function3();
break;
default:
break;
}
switch语句的工作方式是,它会(或多或少)执行转到
跳转到您的case标签,并保留从该点运行。当执行击中破
,它留下的开关组。
The way a switch statement works is that it will (more or less) execute a goto
to jump to your case label, and keep running from that point. When the execution hits a break
, it leaves the switch block.
这篇关于不区分交换机这样的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!