Jump to content

C++ Language/ProgramFlow/BreakStatement/FallthroughInSwitch

From Wikibooks, open books for an open world

This is the current revision of this page, as edited by SoftwareEngineerMoose (discuss | contribs) at 06:53, 21 February 2022. The present address (URL) is a permanent link to this version.

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

A switch statement is an efficient substitute for many if (x==1) {body} else if (x==5) {body} else if (x==99) {body} chains. In a switch statement, each body is a sequence of statements preceded by a case 5: label. If you don't terminate that sequence of statements by break;, then program flow will fall-through and also perform the next sequence of statements. This is often a programming bug, so when you intentionally do this, write [[fallthrough]]; in place of break;.

Additional information about fallthrough (includes interactive examples)