C++ Notes: Switch usage

When to use switch instead of if?

The if statement is used most frequently. However, when a single integral value (char, short, int, long) is used to select from many possibilities, it is better to use switch because the source code is simpler, and therefore the chance of writing an erroneous comparison is less and the code is easier to read and therefore maintain.

The break problem

The break statement at the end of the each switch clause is a major source of errors because it is easy to forget and C++ won't complain. Execution simply continues with the next case. Java was criticized for using adopting the C++ switch statement without fixing this problem. C# has fixed this by making the defualt action at the end of a case to break, and requiring the continue keyword for the unusual case of falling into the next case.

Indenting and spacing switch statements

A typical switch statement uses two levels of indentation: the case keyword is indented one level, and the statements in a case are indented an additional level.

Single, short statements may be written on the same line as the case.

Add blank lines after break statements if that makes the code more readable.

break after last case

Altho there is no need to put a break after the last case, it is good practice so that it isn't forgotten when addition cases are added. Exception: default, if used, should be the last case and there doesn't need to be a break because nothing will ever be added after it.