C++核心準(zhǔn)則ES.70:進行選擇時,switch語句比if語句好

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語句執(zhí)行的時常數(shù)比較運算,相比一系列if-then-else語句,通??梢愿玫乇粌?yōu)化。
A switch enables some heuristic consistency checking. For example, have all values of an enum been covered? If not, is there a default?
switch語句允許某些啟發(fā)式檢查。例如枚舉類型的所有值是否都被覆蓋到了?如果沒有,是否設(shè)置的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).
標(biāo)記和常數(shù)值進行比較的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
覺得本文有幫助?請分享給更多人。
關(guān)注微信公眾號【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
