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(示例)
void use(int n)
{
switch (n) { // good
case 0:
// ...
break;
case 7:
// ...
break;
default:
// ...
break;
}
}
rather than(而不是):
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
新书介绍
以下是本人3月份出版的新书,拜托多多关注!
本书利用Python 的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。
对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。
觉得本文有帮助?欢迎点赞并分享给更多的人。
阅读更多更新文章,请关注微信公众号【面向对象思考】