How to Use the Switch Statement in C++
Conditional statements are a common feature of all programming languages. These statements are used to control the flow of a program and specify when specific blocks of code should be executed.
The main conditional statements used in C++ are if
and if … else
statements. In addition, C++ offers the switch
statement. This statement evaluates an expression against multiple potential cases and executes a block of code if the expression matches that block’s corresponding case. The switch statement behaves similarly to an if
statement that includes many if … else
statements.
In this tutorial, we will discuss—including through an example—how to use the switch statement in C++. We will also discuss how to use the break
, and default
keywords with the switch statement. After reading this guide, you’ll be an expert at using the C++ switch statement.
C++ Conditional Statements
Conditional statements like if
and if … else
are used to make decisions in a program. For instance, an if
statement could instruct a program to run a block of code if a user is over the age of 16, or if it is a Wednesday.
if
and if … else
statements are the most common forms of conditional statements. if
and if … else
statements run a block of code if a condition is true; otherwise, they do nothing. Here’s an example of a C++ if
statement:
int age = 15; if (age > 16) { cout<<"This user is over the age of 16." }
In this example, our code evaluates whether the variable age is greater than 16. If it is, the sentence This user is over the age of 16
. is printed to the console; otherwise, nothing happens. In this case, our user is aged 15 years, so age > 16
evaluates to false. Therefore, the program does not execute the code associated with our if
statement.
But what if you wanted to evaluate against multiple conditions?
That’s where the switch statement comes in. While you can use if … else
statements to evaluate for multiple conditions in an if
statement, this approach can be inefficient and make your code more difficult to read. So, developers often use switch statements to evaluate a statement against multiple potential cases.
C++ switch Statement
The switch statement, also known as a switch … case
statement, allows you to check whether an expression is equal to one of multiple cases. If the stated expression matches (in other words, is equal to) one of the cases in the switch block, the specific code associated with that case will be executed.
switch statements contain one or more case statements. The program uses case statement(s) to declare the condition(s) against which your target expression should be evaluated.
switch statements accept an expression to test, which is surrounded by parentheses, as well as one or more cases against which you want to evaluate your expression. These cases are enclosed within curly brackets.
Here’s the syntax for the C++ switch statement:
switch (expression) { case firstCase: // Code to be executed if expression matches firstCase break; case secondCase: // Code to be executed if expression matches secondCase break; default: // Code to be executed if no expressions are met } }
Here’s the logic for the above switch statement in C++:
- The program evaluates the expression.
- expression is compared with firstCase. If these match, the program will execute the code in the firstCase block. Then, the break keyword will run, which will terminate the switch block.
Note: we discuss the break keyword in a later section of this article. Essentially, this keyword tells the program to move on, past the current switch block.
- If expression does not match firstCase, expression will be compared with secondCase.
- If expression matches secondCase, the program will execute the code inside the secondCase block, and the break statement will terminate the switch block.
- If expression does not match any case in the switch block, the program will execute the contents of the default case statement.
Note: we discuss the concept of the default statement, as it pertains to switch statements, in a later section of this article. default is a keyword that tells the program what to do if none of the case statements within a switch block match the expression.
In a switch statement, the program will first evaluate the first case. If that does not evaluate to true, the program will evaluate subsequent cases until a condition is met or until all conditions are evaluated.
Example of C++ switch
Let’s walk through an example step-by-step to explore how switch statements work in C++.
Suppose we are writing a program that tells us how many days are left until the weekend. In this program, each day of the week will be represented by an integer—for example, Monday will be 1, Tuesday will be 2, Wednesday will be 3, and so on.
This program will take the current day of the week (represented as an integer) and compare it to a set of cases. Each case will direct the program to print out a sentence that states the number of days remaining until the weekend, based on the current weekday.
Here’s the code we could use to accomplish this task:
#include <iostream> include namespace std; int main() { int dayOfWeek = 3; switch (dayOfWeek) { case 1: cout<<"There are 5 days until the weekend!"; break; case 2: cout<<"There are 4 days until the weekend!"; break; case 3: cout<<"There are 3 days until the weekend!"; break; case 4: cout<<"There are 2 days until the weekend!"; break; case 5: cout<<"There is 1 day until the weekend!"; break; } }
Our code returns:
There are 3 days until the weekend.
Let’s break down our code. First, we declare a variable, called dayOfWeek, that stores the current day of the week as an integer. We then use a switch statement that specifies five cases.
First, our program checks to see if dayOfWeek is equal to 1. If it is, our program prints There are 5 days until the weekend!
to the console, after which it breaks out of the switch statement.
If dayOfWeek is not equal to 1, the program evaluates the next case. This will go on until the program evaluates every case in our switch statement—unless one of the cases evaluates to true, at which point a break statement will run and our loop switch statement will terminate.
In our example, we stated that the day of the week is 3—which means it is Wednesday. As a result, our program prints There are 3 days until the weekend!
to the console. Then, our program terminates the switch block of code and continues running the main program.
C++ Break
C++ switch statements usually use the break keyword in each case, like we did in the example above. When the program executes a break statement, the code within a given block will stop executing and the rest of the program will continue to run.
break statements are often used with switch statements because they stop the program from evaluating the rest of the cases in the switch statement.
"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"
Venus, Software Engineer at Rockbot
Here’s an example of the break keyword in a switch statement, taken from our extended example above:
… case 3: cout<<"There are 3 days until the weekend!"; break; …
So, in the above example, if dayOfWeek is equal to 3, our program will execute a break statement so that no more cases are evaluated. This makes sense because if dayOfWeek is equal to 3, it cannot be equal to 4 or 5, which are the next cases in our switch statement.
If dayOfWeek is equal to 3, the message There are 3 days until the weekend!
is printed to the console. Then, the switch statement stops executing because a break statement directs the program to move on past the switch block.
C++ Default
In C++, the optional default case keyword tells our code what to do if no case evaluates to true.
In our above example, our code only accounts for weekdays. So, if it is already the weekend, our program will do nothing. If we use a default code statement, we can instruct our code to perform an action if none of our cases are met.
Suppose we wanted to print the message It’s the weekend!
to the console if it were Saturday or Sunday. We could use our switch statement example from above and the following code to accomplish this task:
… case 5: cout<<"There is 1 day until the weekend!"; break; default: cout<<"It's the weekend!"; break; …
According to this code, if dayOfWeek is not equal to any of the cases we specified—or, in other words, if dayOfWeek is equal to 6 or 7—the contents of the default statement will be executed. So, if today were Saturday, for example, the following message would be printed to the console:
It's the weekend!
Conclusion
The switch statement is used in C++ to evaluate a statement against multiple possible outcomes. If one of these expressions evaluates to true, the program will execute the code associated with that outcome. If no expressions evaluate to true, the program will execute the contents of a default statement, if specified.
This tutorial discussed, with an example, how to use the C++ switch statement and how to use the break, and default keywords with switch. Now you’re ready to start using switch statements in your code like a pro!
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.