为什么选择 Switch/Case 而不是 If/Else If?

这个问题主要针对 C/C++,但我猜其他语言也有关系.

This question in mainly pointed at C/C++, but I guess other languages are relevant as well.

我不明白为什么仍然使用 switch/case 而不是 if/else if.在我看来,这很像使用 goto,并导致相同类型的混乱代码,而使用 if/else if 可以以更有条理的方式实现相同的结果.

I can't understand why is switch/case still being used instead of if/else if. It seems to me much like using goto's, and results in the same sort of messy code, while the same results could be acheived with if/else if's in a much more organized manner.

不过,我还是经常看到这些街区.找到它们的常见位置是在消息循环(WndProc...)附近,而这些位置是它们造成最严重破坏的地方:变量在整个块中共享,即使不合适(并且不能在里面初始化).必须特别注意不要放弃休息,等等......

Still, I see these blocks around quite often. A common place to find them is near a message-loop (WndProc...), whereas these are among the places when they raise the heaviest havoc: variables are shared along the entire block, even when not propriate (and can't be initialized inside it). Extra attention has to be put on not dropping break's, and so on...

就我个人而言,我避免使用它们,我想知道我是否遗漏了什么?

Personally, I avoid using them, and I wonder wether I'm missing something?

它们是否比 if/else 更有效?它们是按照传统进行的吗?

Are they more efficient than if/else's? Are they carried on by tradition?

推荐答案

总结一下我最初的帖子和评论 - switch 语句相比 if/else 声明:

Summarising my initial post and comments - there are several advantages of switch statement over if/else statement:

  1. 更简洁的代码.具有多个链式 if/else if ... 的代码看起来很凌乱且难以维护 - switch 提供更清晰的结构.

  1. Cleaner code. Code with multiple chained if/else if ... looks messy and is difficult to maintain - switch gives cleaner structure.

性能.对于密集的 case 值,编译器生成跳转表,对于稀疏 - 二分查找或一系列 if/else,所以在最坏的情况下 switchif/else 一样快,但通常更快.虽然有些编译器可以类似地优化 if/else.

Performance. For dense case values compiler generates jump table, for sparse - binary search or series of if/else, so in worst case switch is as fast as if/else, but typically faster. Although some compilers can similarly optimise if/else.

测试顺序无关紧要.为了加快一系列 if/else 测试,需要首先放置更多可能的案例.有了switch/case,程序员就不需要考虑这个了.

Test order doesn't matter. To speed up series of if/else tests one needs to put more likely cases first. With switch/case programmer doesn't need to think about this.

默认值可以是任何地方.if/else 的默认大小写必须在最后 - 在最后一个 else 之后.在 switch - default 可以在任何地方,只要程序员认为它更合适.

Default can be anywhere. With if/else default case must be at the very end - after last else. In switch - default can be anywhere, wherever programmer finds it more appropriate.

通用代码.如果您需要在几种情况下执行通用代码,您可以省略 break 并且执行将失败" - 这是您无法使用 if/else.(对于这种情况,放置一个特殊的注释 /* FALLTHROUGH */ 是一个很好的做法 - lint 识别它并且不会抱怨,没有这个注释它会抱怨,因为这是忘记的常见错误 <代码>中断).

Common code. If you need to execute common code for several cases, you may omit break and the execution will "fall through" - something you cannot achieve with if/else. (There is a good practice to place a special comment /* FALLTHROUGH */ for such cases - lint recognises it and doesn't complain, without this comment it does complain as it is common error to forgot break).

感谢所有评论者.

相关文章