Switch Statement in C++

Switch-statement-in-C-Featured-image.jpg

The switch statement in C++ is a powerful control flow structure that simplifies decision-making in programming. It executes different blocks of code based on the value of a single expression. It is an efficient alternative to if-else if chains, whether for creating a simple calculator or making decisions easily based on user input.  In this article, we will discuss what is switch statement is in C++, its syntax, working, flowchart, rules, examples, advantages and disadvantages, and the difference between a C++ switch case and an if-else if statement.

Table of Contents:

What is switch Statement in C++?

The switch statement in C++ is a control flow structure that is used to execute different blocks of code based on the value of a single expression. The value of the expression is typically an integer or an enum. It is an alternative to using multiple if-else statements when the same variable is checked using multiple constant values. It has three keywords: switch, case, and default.

Example:

Cpp

Output:

switch Statement in C++ Example

The code shows how a switch statement is used to print the name of the day based on the integer value of the day, and since the day is 3, thus, it prints “Wednesday” as a result.

Syntax of switch Statement in C++

The general syntax of the switch statement in C++ is as follows:

switch (expression) {
case constant1:
// Code to execute if expression == constant1
break;
case constant2:
// Code to execute if expression == constant2
break;
// More cases as needed
default:
// Code to execute if no case matches
}

Here,

  • expression: It is a value or variable that is evaluated.
  • case constant1: It is a possible value of the expression, and if the expression is equal to constant1, then the corresponding code block will be executed.
  • break: It terminates the switch statement and also prevents switching to the next case.
  • default: It is an optional case that will be executed if no other case matches.

Keywords Used in C++ Switch Statement: switch, case, default

There are three keywords in the switch statement in C++:

1. switch

  • It starts the C++ switch case and also takes an expression to evaluate.
  • Example: switch (value)

2. case

  • It defines the individual constant values to compare with the switch expression.
  • Each case executes the code block within it.
  • Example: case 1:

3. default

  • It is an optional keyword that will be executed if no other case matches.
  • It works like an else in an if-else statement.
  • Example: default:

Flowchart of switch Statement in C++

Flowchart of Switch Statement in C++

How the switch Statement Works in C++

Here is a step-by-step description of the working of the switch statement in C++:

Step 1: Evaluate the expression

The switch expression is to be evaluated once.

Step 2: Match the values with the cases

The value of the expression is compared with each case.

  • If a match is found, then the code in that case is executed.
  • If no match is found, then the default case is found.

Step 3: Exit with the break

  • If a matching case is found, then its code block is executed, and the break statement will exit the C++ switch case. 
  • If no break is found, then the next case is executed.

Step 4: Default Case

If no cases match the value of the expression, then the code under the default case is executed.

Rules of switch Statement in C++ 

Below are the rules that must be followed by using the switch case statement in C++:

  1. The switch statement only supports an integral type, such as int, char, and enum.
  2. Any number of cases can be used in the switch statement.
  3. A case label must be constant and cannot be variable.
  4. Each case label must be unique in the switch block.
  5. The break statement is optional, but each case statement can have a break.
  6. Each case block has its own scope.

C++ switch Statement Examples

Below are a few examples of switch statements in C++:

Example 1: Simple Calculator using the switch

Cpp

Output:

Example 1: Simple Calculator using the switch

The code shows how a simple calculator can be created using the switch statement that can perform basic arithmetic operations such as addition, subtraction, multiplication, and division. In this calculator, first you need to enter a number, then an operator for the operation, and lastly another number, and then the result will be printed. Since the first number is 10, the operator is * for multiplication, and the second number is 20, thus, the result is 200.

Example 2: Printing Messages based on a Grade without Using break

Cpp

Output:

Example 2: Printing Messages based on a Grade without Using break

The code shows how a switch statement is used to categorize the student’s grade, and without a break, multiple messages are printed as per the grade obtained by the student. Here, the grade is B, so “Well done! Good job! You passed! Better luck next time!” is printed as the result.

Get 100% Hike!

Master Most in Demand Skills Now!

Example 3: Using switch with enum for Day of the Week

Cpp

Output:

Example 3: Using switch with enum for Day of the Week

The code shows how the switch statement is used with an enum to print the message based on the day of the week that whether it is the start, middle, or end of the week. Here, today is already set as Wednesday, thus, the output “Midweek!” is printed to the console.

Example 4: Switch with Default Case

Cpp

Output:

Example 4: Switch with Default Case

The code shows how a switch statement with a default case is used to check whether the number entered matches the cases or not. Here, the number entered is 5, thus, the result “Invalid number! Please enter a number between 1 and 3” is printed to the console.

Example 5: Categorizing Months Using switch Statement

Cpp

Output:

Example 5: Categorizing Months Using Switch Statement

The code shows how a switch statement categorizes the months into the seasons. Since the month is 10, the output “Autumn” is printed to the console.

Difference between switch and if-else if ladder in C++

Here is the comparison table that shows the differences between switch and if-else if ladder, which helps to understand C++ control flow statements.

Feature switch if-else if ladder
Expression Type Works with constant values (e.g., int, char, enum) Can handle any expression (e.g., relational, logical)
Performance Often faster for many cases Slower for large conditions
Complex Conditions Cannot evaluate ranges or complex expressions Can handle complex conditions
Switching to Other Case Allows switching when the break is not present No switching and stops at the first true condition
Default Handling Can use a default case (optional) Requires an else block for unmatched conditions
Use Cases Best for comparing a variable with constant values Suitable for more complex or dynamic conditions
Limitations Limited to constant value comparisons No limitations on condition complexity
Syntax switch(expression) { case: … } if(condition) { … } else if { … }

Advantages of switch Statement in C++

  1. Clean and Organized Syntax: It provides a clean and organized way to handle multiple constant conditions efficiently. This makes it a great part of C++ decision-making statements.
  2. Better Performance: The switch statement is often faster than if-else due to compiler optimizations.
  3. Simplifies Code: It helps in minimizing the need for using if-else if by making the code simpler and easier to understand.
  4. Default Case Handling: The switch statement provides a default case to find the unmatched values easily.
  5. Ease of Modification: It is easier to modify the cases when handling many fixed values.
  6. Clear Structure: The structure of the switch statement is clear and easy to understand.

Disadvantages of switch Statement in C++

  1. Limited Data Types: It only supports integral values such as int, char, or enum, and doesn’t support float, double, or string.
  2. No Complex Conditions: Logical or relational expressions cannot be used in the case labels.
  3. Fall-Through Issue: Removing the break can cause switching to the next case unintentionally, which can lead to bugs. This is a crucial point regarding the break and default in the C++ switch statement.
  4. Less Flexible: The switch statement is less flexible when conditions are based on ranges or multiple variables.
  5. No Case Grouping with Expressions: The cases cannot be grouped together using expressions like those in if-else.

Conclusion

The switch statement in C++ is an important control structure that can handle multiple constant values easily. It has clear syntax and gives better performance than an if-else if statement. However, it has rules, advantages, and disadvantages too. So, by understanding how a C++ switch statement works, what the rules are that must be followed when dealing with a switch statement, advantages and disadvantages, you can easily write a C++ program using the switch statement.

If you’re getting ready for interviews, these C++ interview questions are a great place to start.

Useful Resources:

Switch Statement in C++ – FAQs

Q1. Can switch work with strings?

No, a switch statement only supports int, char, and enum.

Q2. What if I skip a break in a case?

If you skip a break in a case, then the next case will also execute.

Q3. Is the default case required?

No, it is not required. It is optional, but it’s good to use the default case for unmatched cases.

Q4. Can two cases share the same code?

Yes, you only have to stack them without a break in between.

Q5. Is switch faster than if-else?

Yes, switch is faster than if-else with many constant cases.

Q6. Which data types are allowed in a C++ switch statement?

The switch statement in C++ only supports integral types such as int, char, and enum. Types like float, double, or string are not allowed.

Q7. How does fall-through work in a C++ switch statement?

Fall-through occurs when a case does not have a break statement, causing the execution to continue into the next case. This can be useful but requires careful handling to avoid bugs.

Q8. Can a switch statement evaluate multiple variables at once?

No, a C++ switch statement evaluates only a single expression. For multiple variables, you must use nested switches or if-else statements.

Q9. What are common mistakes when using switch statements in C++?

Common mistakes include forgetting the break statement, using non-constant expressions for cases, and trying to use unsupported data types like float or string.

Q10. When should I choose switch over if-else in C++?

You can use a switch statement when you need to compare a single variable against multiple constant values. It is cleaner, easier to read, and often faster than multiple if-else statements.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner