在我的第一次代码评审中(不久前),有人告诉我,在所有switch语句中包含一个default子句是一种很好的实践。我最近想起了这个建议,但不记得理由是什么了。现在我听起来很奇怪。

是否有一个合理的理由总是包含默认语句? 这是语言依赖吗?我不记得当时我在用什么语言了——也许这适用于一些语言而不是其他语言?


当前回答

这取决于switch在特定语言中的工作方式,但是在大多数语言中,当没有匹配到case时,switch语句的执行就会毫无警告地结束。想象一下,你期望得到一组值,并在switch中处理它们,然而你在输入中得到了另一个值。什么都没发生,你也不知道什么都没发生。如果您发现了违约情况,您就会知道有问题。

其他回答

开关情况几乎总是有一个默认情况。

使用默认值的原因

1.“捕捉”一个意外值

switch(type)
{
    case 1:
        //something
    case 2:
        //something else
    default:
        // unknown type! based on the language,
        // there should probably be some error-handling
        // here, maybe an exception
}

2. 处理“默认”操作,其中的case是针对特殊行为的。

您在菜单驱动程序和bash shell脚本中经常看到这种情况。当变量声明在switch-case之外但没有初始化时,您也可能会看到这种情况,并且每个case初始化它为不同的东西。这里的默认值也需要初始化它,以便访问变量的代码不会引发错误。

3.向阅读您的代码的人展示您已经覆盖了这种情况。

variable = (variable == "value") ? 1 : 2;
switch(variable)
{
    case 1:
        // something
    case 2:
        // something else
    default:
        // will NOT execute because of the line preceding the switch.
}

这是一个过于简化的例子,但关键是阅读代码的人不应该怀疑为什么变量不能是1或2以外的东西。


我能想到的唯一不使用默认值的情况是,当开关正在检查一些非常明显的东西时,其他选项都可以愉快地忽略

switch(keystroke)
{
    case 'w':
        // move up
    case 'a':
        // move left
    case 's':
        // move down
    case 'd':
        // move right
    // no default really required here
}

这取决于switch在特定语言中的工作方式,但是在大多数语言中,当没有匹配到case时,switch语句的执行就会毫无警告地结束。想象一下,你期望得到一组值,并在switch中处理它们,然而你在输入中得到了另一个值。什么都没发生,你也不知道什么都没发生。如果您发现了违约情况,您就会知道有问题。

在某些情况下,没有默认情况实际上是有益的。

If your switch cases are enums values, by not having a default case, you can get a compiler warning if you are missing any cases. That way, if new enum values are added in the future and you forget to add cases for these values in the switch, you can find out about the problem at compile time. You should still make sure the code takes appropriate action for unhandled values, in case an invalid value was cast to the enum type. So this may work best for simple cases where you can return within the enum case rather than break.

enum SomeEnum
{
    ENUM_1,
    ENUM_2,
    // More ENUM values may be added in future
};

int foo(SomeEnum value)
{
    switch (value)
    {
    case ENUM_1:
        return 1;
    case ENUM_2:
        return 2;
    }
    // handle invalid values here
    return 0;
 }

enum所使用的开关可能不需要默认大小写。当switch包含所有值时,默认情况将永远不会执行。所以在这种情况下,这是不必要的。

如果switch语句中没有缺省情况,则在缺省情况下行为可能是不可预测的 在某个时间点出现,这在发展阶段是无法预测的。这是一个很好的练习 要包含默认大小写。

switch ( x ){
  case 0 : { - - - -}
  case 1 : { - - - -}
}

/* What happens if case 2 arises and there is a pointer
* initialization to be made in the cases . In such a case ,
* we can end up with a NULL dereference */

这样的做法可能会导致错误,如NULL解引用,内存泄漏以及其他类型的 严重的错误。

例如,我们假设每个条件初始化一个指针。但如果默认情况是 应该是上升的,如果我们不初始化这个例子,那么就完全有可能上升 一个空指针异常。因此,建议使用默认case语句,即使它 可能是微不足道的。