Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

Why not rely on implicit sinking of switch statements in C++?

Shulou Source: shulou.com Published: 2022-06-01 19:30:26 10月03日 Update

This article mainly explains the "why do not rely on the implicit sinking of switch sentences in C++", the content of the explanation in the article is simple and clear, easy to learn and understand, now please follow the editor's train of thought slowly in depth, together to study and learn why do not rely on the implicit sinking of switch sentences in C++!

ES.78: don't rely on implicit sinking of switch statements

Reason (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.

Typically, break is used to abort a non-empty case processing. Accidentally missing a break is usually a mistake. Intentional sinking treatment may bring maintenance risks and should be used less and explicitly.

Example (sample)

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:

There is no problem with multiple tags in a statement.

Switch (x) {

Case'asides:

Case'baked:

Case'fags:

Do_something (x)

Break

}

Return statements in a case label are also OK:

There is no problem using the return statement in the case tag:

Switch (x) {case'asides: return 1; case'baked: return 2; case'cages: return 3;}

Exceptions (exception)

In rare cases if fallthrough is deemed appropriate, be explicit and use the [[fallthrough]] annotation:

In rare cases, if you are sure that the sinking treatment is appropriate, you can clearly indicate it using [[fallthrougn]] notation.

Switch (eventType) {

Case Information:

Update_status_bar ()

Break

Case Warning:

Write_event_log ()

[[fallthrough]]

Case Error:

Display_error_window ()

Break

} Note (Note) Enforcement (implementation recommendation)

Flag all implicit fallthroughs from non-empty cases.

Marks all implicit sinking processing from a non-empty case.

Thank you for your reading, the above is the content of "Why do not rely on the implicit sinking of switch sentences in C++". After the study of this article, I believe you have a deeper understanding of why C++ should not rely on the implicit sinking of switch sentences, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Processing sentences situations problems learning content tags appropriateness accidents reasons multiple that is suggestions ideas articles more tags knowledge knowledge points Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info vpn OPPO Reno Shulou Information Linux