切换语句失败...应该允许吗? [英] Switch statement fall-through...should it be allowed?

查看:19
本文介绍了切换语句失败...应该允许吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从我记事起,我就一直避免使用 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;
   }

这样,只要 case 为 0, 1,它就会在 switch 语句中执行所有操作.我在设计上看到了这一点,我只是不知道我是否同意应该以这种方式使用 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 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++ FAQ 定义 "evil"

And please note that I use the C++ FAQ definition of "evil"

这篇关于切换语句失败...应该允许吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆