Switch statements in C++ are marvels of speed and readability. They’re an essential component of controlling the execution flow of a C++ program, yet are often ignored in favor of their more common sibling: the if-else statement. In fact, switch statements have many uses that make them far superior to if-else statements. Keep reading to learn some useful specifics.
What Is the Switch Statement in C++?
The switch statement allows a program to change its execution based on context. But any C++ developer will know that not all programs are linear, and therefore do not execute the same way under all circumstances. switch statements allow programs to recognize these different contexts and, based on them, execute different branches of code.
How To Use the C++ Switch Statement
The switch statement evaluates the expression given to it as an argument in order to determine which section of code to execute next. Depending on the value of the expression, the program executes different sections of code.
There are three main parts of a switch statement: (i) the switch expression that is evaluated and branched from; (ii) specific cases containing sections of code to be executed; and, (iii) a default case, executed when the switch expression fits no other cases.
These three parts are all you need to construct some basic branches in your program execution. For instance, if you wanted to execute a branch program based on the value of a + b, you would use the switch statement like so:
Here, if a + b = 2, the program will branch and execute the code you’d write after case 2. If a + b = 4, the program will execute the code under case 4. And if the switch expression doesn’t evaluate to any of the specified cases (e.g., if a + b = 7), then the default case will be executed.
When To Use a Switch Statement in C++
Remember, switch statements need expressions that can be neatly evaluated into constants. So if your expression has a set of defined values into which it can be predictably evaluated, the switch statement makes for an excellent tool. For example, if your program sorts students based on their letter grades, the switch statement can work as follows:
In addition, if there’s a small number of cases overall, it’s prudent to use the switch statement due to its speed and readability. Comparing simple expressions to constants is easy for C++ compilers and makes for fast execution.
When To Avoid Using Switch Statements in C++
Because switch statements need to evaluate to a constant value, they only work with discrete expressions. If we want to execute different sections of code based on a range of values (e.g., when grades are marked out of 100), then we’d need several switch statements, rendering our code unreadable and unmaintainable.
In addition, the separation between the expression and its result can make long switch statements hard to read. Even if your code may not use a lot of cases now, adding more and more cases to a switch statement over time can be a program-breaking endeavor. Because switch statements operate on discrete values, you have to cater to every possible one. And you may well end up with a lot of values.
For instance, returning to the student grades example above, if the school adds + and – to its grading system, we’ll have to add 10 new cases, and that’s assuming F grades can’t be followed by + or -.
Instead, when a switch statement gets too long, you’re better off restructuring the program to remove the need for so many branches and cases.
Other Ways To Control Program Flow in C++
By no means are switch statements the only form of flow control you can use in your program.
if-else statements are the obvious and most widely used contender, controlling execution flow based on Boolean expressions. Instead of the constants to which switch expressions must evaluate, if-statement expressions must be either true or false. This makes them extremely flexible to use; however, they can be much slower for compilers to execute and hard to read, to say nothing of nested if statements.
Yet another option is a loop, which executes sections of code continuously so long as a particular condition is met. Loops help immensely when we want to avoid repeating code or having to click “run” 50 times. There are two types of loops: for loops and while loops.
for loops run continuously for a certain number of iterations, until a counter value is reached. They contain three statements: (i) an opening statement executed before the start of the first iteration; (ii) an execution condition that must be met for the next iteration to continue; and, (iii) a post-execution statement run after the section of code has finished an iteration.
while loops continuously run until a particular condition is not met:
We can also stop loop execution entirely (using the break statement) or skip to the end of the current loop iteration (using the continue statement).
Branch Prediction in C++
Using the grades example above, what if our program already knew that a student received an “F” and could jump straight to the “F” section, without first having to go through “A” to “E”? In fact, computer processors can already do this using branch predictors.
While your program runs normally, your CPU’s branch predictor skips ahead and tries to predict which branches the code will take before the program reaches them. The program asks the CPU to speculate and execute the most likely branches. If the speculations are incorrect, the CPU must undo or discard any operations from branches that shouldn’t be run. However, if the speculations are right they can save a lot of time.
Linux includes the macros likely and unlikely, which allow developers to pass a hint to the C++ compiler as to which branches in the code the programs are likely (or unlikely) to run?.
Become a C++ Developer
The switch statement has its uses. Make sure to use it well to improve your code’s readability and speed, but remember to avoid it when you need to branch based on ranges of values and not discrete constants. While it’s great in the situations we looked at above, for other use cases don’t forget if-else statements and loops, which work well in their own right.
To keep learning about interesting aspects of C++ coding like the switch statement, enroll in our expert-taught C++ Nanodegree program. By allowing you to code real-world projects, you’ll master topics like C++ language features, common programming paradigms and more.