switch语句应始终包含默认子句吗? [英] Should switch statements always contain a default clause?

查看:356
本文介绍了switch语句应始终包含默认子句吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的第一篇代码回顾中(有一段时间),我被告知,在所有switch语句中都包含default子句是一种很好的做法。我最近记得了这个建议,但不记得有什么道理。现在听起来对我来说很奇怪。

In one of my first code reviews (a while back), I was told that it's good practice to include a default clause in all switch statements. I recently remembered this advice but can't remember what the justification was. It sounds fairly odd to me now.


  1. 是否有一个明智的理由总是包含默认语句?

  1. Is there a sensible reason for always including a default statement?

该语言依赖吗?我不记得当时使用的是哪种语言-也许这适用于某些语言,而不适用于其他语言?

Is this language dependent? I don't remember what language I was using at the time - maybe this applies to some languages and not to others?


推荐答案

切换用例应该几乎总是使用默认值用例。

Switch cases should almost always have a default case.

使用默认值

Reasons to use a default

的原因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。要处理默认操作(这种情况属于特殊情况)。

您会在菜单驱动程序和bash shell脚本中看到很多。当变量在switch-case之外声明但未初始化时,您可能还会看到此情况,并且每种情况都会将其初始化为不同的东西。在这里,默认值也需要对其进行初始化,以使访问该变量的行代码不会引发错误。

You see this a LOT in menu-driven programs and bash shell scripts. You might also see this when a variable is declared outside the switch-case but not initialized, and each case initializes it to something different. Here the default needs to initialize it too so that down the line code that accesses the variable doesn't raise an error.

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.
}

这是一个过于简化的示例,但要点是有人在阅读代码不应该奇怪为什么 variable 不能是1或2以外的东西。

This was an over-simplified example, but the point is that someone reading the code shouldn't wonder why variable cannot be something other than 1 or 2.

我想到的唯一不使用 default 的情况是,当开关正在检查其相当明显的其他选择都可以被幸福忽略的东西时

The only case I can think of to NOT use default is when the switch is checking something where its rather obvious every other alternative can be happily ignored

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

这篇关于switch语句应始终包含默认子句吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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