C++核心准则ES.70:进行选择时,switch语句比if语句好

2020-05-29 14:58:37 浏览数 (1)

ES.70: Prefer a switch-statement to an if-statement when there is a choice

ES.70:进行选择时,switch语句比if语句好

Reason(原因)

  • Readability.
  • 可读性
  • Efficiency: A switch compares against constants and is usually better optimized than a series of tests in an if-then-else chain.
  • 效率:switch语句执行的时常数比较运算,相比一系列if-then-else语句,通常可以更好地被优化。
  • A switch enables some heuristic consistency checking. For example, have all values of an enum been covered? If not, is there a default?
  • switch语句允许某些启发式检查。例如枚举类型的所有值是否都被覆盖到了?如果没有,是否设置的default选项?

Example(示例)

代码语言:javascript复制
void use(int n)
{
    switch (n) {   // good
    case 0:
        // ...
        break;
    case 7:
        // ...
        break;
    default:
        // ...
        break;
    }
}

rather than(而不是):

代码语言:javascript复制
void use2(int n)
{
    if (n == 0)   // bad: if-then-else chain comparing against a set of constants
        // ...
    else if (n == 7)
        // ...
}
Enforcement(实施建议)

Flag if-then-else chains that check against constants (only).

标记和常数值进行比较的if-then-else判断链(只限于这种情况)

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es70-prefer-a-switch-statement-to-an-if-statement-when-there-is-a-choice


觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

0 人点赞