C++核心準則ES.78:不要依靠switch語句的隱式下沉處理

ES.78: Don't rely on implicit fallthrough in?switch?statements
ES.78:不要依靠switch語句的隱式下沉處理
Reason(原因)
Always end a non-empty?case?with a?break. Accidentally leaving out a?break?is a fairly common bug. A deliberate fallthrough can be a maintenance hazard and should be rare and explicit.
通常情況下使用break中止一個非空case處理。意外漏掉某個break通常是一個錯誤。故意的下沉處理可能帶來維護風險,應該少用并明示用法。
Example(示例)
switch (eventType) {
case Information:
update_status_bar();
break;
case Warning:
write_event_log();
// Bad - implicit fallthrough
case Error:
display_error_window();
break;
}
Multiple case labels of a single statement is OK:
一個語句中包含多個標簽是沒有問題的。
switch (x) {
case 'a':
case 'b':
case 'f':
do_something(x);
break;
}
Return statements in a case label are also OK:?
case標簽中使用返回語句也沒有問題:
switch (x) {case 'a':? return?1;??case?'b':?? return?2;??case?'c':?? return?3;??}
Exceptions(例外)
In rare cases if fallthrough is deemed appropriate, be explicit and use the?[[fallthrough]]?annotation:
在很少的情況下,如果確信下沉處理是合適的,可以使用[[fallthrougn]]記法明確標明。
switch (eventType) {
case Information:
update_status_bar();
break;
case Warning:
write_event_log();
[[fallthrough]];
case Error:
display_error_window();
break;
}Note(注意)
Enforcement(實施建議)
Flag all implicit fallthroughs from non-empty?cases.
標記所有來自非空case的隱式下沉處理。
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es78-dont-rely-on-implicit-fallthrough-in-switch-statements
覺得本文有幫助?請分享給更多人。
關注微信公眾號【面向?qū)ο笏伎肌枯p松學習每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
