Switch Statement in C++

Switch Statement in C++

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 in C++, its syntax, working, flowchart, rules, examples, advantages and disadvantages, and difference between a switch statement and an if-else if statement in C++.

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 in switch Statement in C++

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

1. switch

  • It starts the switch statement 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++

Working of switch Statement 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 switch statement. 
  • If no break is found, then the next case is executed.

Step 4: Default Case

If no cases match with 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 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.

Examples of switch Statement in C++

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++

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. It provides a clean and organized way to handle multiple constant conditions efficiently.
  2. The switch statement is often faster than if-else due to compiler optimizations.
  3. It helps in minimizing the need for using the if-else if by making the code simpler and easier to understand.
  4. The switch statement provides a default case to find the unmatched values easily.
  5. It is easier to modify the cases when handling many fixed values.
  6. The structure of the switch statement is clear and easy to understand.

Disadvantages of switch Statement in C++

  1. It only supports integral values such as int, char, or enum, and doesn’t support float, double, or string.
  2. Logical or relational expressions cannot be used in the case labels.
  3. Removing the break can cause switching to the next case unintentionally, which can lead to bugs.
  4. The switch statement is less flexible when conditions are based on ranges or multiple variables.
  5. 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 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.

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.

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