Switch语句掉线...应该允许吗? [英] Switch statement fall-through...should it be allowed?
问题描述
只要我记得我就避免使用switch语句掉线。实际上,我不记得它曾经作为一种可能的方式进入我的意识,因为它早在我的脑海中就被深深地钻了出来,因为它只不过是switch语句中的一个错误。但是,今天,我遇到了一些设计上使用它的代码,这让我立即想知道社区中的每个人对switch语句失败的看法。
For as long as I can remember I have avoided using switch statement fall-through. Actually, I can't remember it ever entering my consciousness as a possible way to do things as it was drilled into my head early on that it was nothing more than a bug in the switch statement. However, today I ran across some code that uses it by design, which got me immediately wondering what everyone in the community thinks about switch statement fall-through.
是吗?编程语言应该明确不允许(像C#一样,尽管它提供了一种解决方法),或者它是任何一种足以使程序员掌握的语言功能吗?
Is it something that a programming language should explicitly not allow (like C# does, though it supplies a workaround) or is it a feature of any language that is powerful enough to leave in the programmer's hands?
编辑::
我对落空的含义还不够具体。我经常使用这种类型:
I wasn't specific enough to what I meant by fall-through. I use this type a lot:
switch(m_loadAnimSubCt){
case 0:
case 1:
// Do something
break;
case 2:
case 3:
case 4:
// Do something
break;
}
但是,我担心这样的事情。
However, I'm concerned about something like this.
switch(m_loadAnimSubCt){
case 0:
case 1:
// Do something, but fall through to the other cases
// after doing it.
case 2:
case 3:
case 4:
// Do something else.
break;
}
这样,当大小写为0、1时,它将完成切换中的所有操作声明。我从设计上就已经看到了这一点,但我不知道是否同意以这种方式使用switch语句。我认为第一个代码示例非常有用且安全。第二种似乎很危险。
This way whenever the case is 0, 1 it will do everything in the switch statement. I've seen this by design and I just don't know if I agree that switch statements should be used this way. I think the first code example is a very useful and safe. The second seems kind of dangerous.
推荐答案
这可能取决于您认为的失败之处。我对这种事情没事:
It may depend on what you consider fallthrough. I'm ok with this sort of thing:
switch (value)
{
case 0:
result = ZERO_DIGIT;
break;
case 1:
case 3:
case 5:
case 7:
case 9:
result = ODD_DIGIT;
break;
case 2:
case 4:
case 6:
case 8:
result = EVEN_DIGIT;
break;
}
但是,如果您有一个case标签,后跟代码可转至另一个case标签,我几乎总是认为那是邪恶的。也许将通用代码移至函数并从两个地方调用都是更好的主意。
But if you have a case label followed by code that falls through to another case label, I'd pretty much always consider that evil. Perhaps moving the common code to a function and calling from both places would be a better idea.
并且请注意,我使用了 C ++常见问题解答 邪恶
And please note that I use the C++ FAQ definition of "evil"
这篇关于Switch语句掉线...应该允许吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!