Home Resource Centre Switch Case In C++ (Statement), Uses, Break & More With Examples

Switch Case In C++ (Statement), Uses, Break & More With Examples

In C++, a variable can be verified for equality against a list of values using the switch case statement. Every such instance is denominated as a case, and the variable being switched on is checked for each case. It offers a quick technique to distribute execution to different areas of code depending on the value of the expression, as opposed to the lengthy if-else-if ladder statement.

What Is A Switch Statement/ Switch Case In C++?

In C++ language, a switch statement is a flow control statement that enables program to check the equality of a variable against a set of possible values known as cases. The switch statement examines a specified phrase and then executes the statements linked to it based on the evaluated value.

Let's look at the simple syntax for the switch statement, which shows how to use it in code. 

Syntax:

switch (expression) {
case value1:
// code to be executed if
// expression is equal to constant1;
break;
case value2:
// code to be executed if
// expression is equal to constant2;
break;
.....
.....
default code:
// code to be executed if
// expression doesn't match any constant
break;}

Here,

  • The switch is the keyword for the statement.
  • (expressions) represents the value against each case value is evaluated.
  • The block of code associated with/ following the case value is what is executed if the expression and the case value match.
  • The break keyword terminates the switch statement after the corresponding case has been executed.

Note: In the absence of a break statement, the code will keep running through successive cases until it encounters either a break or reaches the end of the switch expression.

Program to show and explain the declaration of the switch statement in C++

Output:

Enter an operator (+, -, *, /): +
Enter two numbers:
2 3
2 + 3 = 5

Note: You can enter any operator and any two numbers of your choice.

Code Explanation:

  1. We declare a character type variable called oper and two floating data type variables, num1 and num2, in the main() function.
  2. Next, we use the cout statement to print the phrase Enter an operator (+, -, *, /): which prompts the user to enter an operator of their choice. This input is then scanned using the cin statement.
  3. The program again uses the cout statement to prompt the user to enter two numbers which are scanned with the cin statement.
  4. We then initiate the switch statement, where the program checks the cases for the operator the user selected. 
  5.  The user-supplied value is the addition arithmetic operator (+), which matches the case value 1. The statement then executes the code block following this case, which performs the addition mathematical operation in the number provided by the user. 
  6. The cout statement prints the result of the operation on the output window and the break keyword terminates the switch statement.
  7. The program seizes execution with the return 0 statement. 

Note: This C++ program asks the user to enter two numbers and one of the operators (+, -, *, or /) before using a switch statement to carry out the necessary arithmetic operation. The program generates an error notice if the operator is not one of the acceptable selections.

Rules Of Switch Case In C++

There are a few rules that must be complied with when using switch case statements in a C++ langauge. They are as follows:

1. The output of a switch expression should be a constant.

The outcome of the expression must be a constant value. It would not be valid if the expression used in the switch statement did not produce a constant value.

2. Break keyword in switch case

The statements after a case will run until a break statement is reached when the variable that is being turned on equals that case.

3. Default keyword in switch case

An optional default case that must come at the end of a switch statement is permitted. When none of the situations apply, a case can be completed using the default case.

4. Only int or char type values can be evaluated by an expression.

The switch statement can evaluate only character or numeric values. So only values of type int or char should be returned by the switch expression.

5. Duplicate case values are not allowed

All the case values should be unique. Identical case values are not allowed.

6. Nested switch statement

You can nest switch statements, which means placing one switch statement inside another. Nested switch statements, on the other hand, need to be avoided because they add complexity and make the program harder to read.

How Does Switch Case In C++ Work?

We know that the purpose of the C++ switch case/ switch statement is to compare an expression to the value of the cases and then make the decision regarding which block of code must be executed.

  • So the switch case works by first comparing the expression with case values.
  • If the expression matches one of the cases, the block of code corresponding to that case is run.
  • Then the execution halts, and the switch statement expires in the event of an interrupt.
  • In contrast, if the first case and expression values do not match, then the flow of control jumps to the following case.
  • The process of comparing the expression and value of the next case is repeated for the second case. And the next section's code is executed if a match is found.
  • This process keeps on repeating, and the flow of control will keep shifting to subsequent cases until one of the case values matches the expression. Or until the switch case statement comes to an end.
  • In case a default block exists, it is executed before the switch statement expires.

The Flow Chart Of Switch Case In C++

This flowchart demonstrates the fundamental format of a C++ switch statement.

  • At the onset of a switch statement, an evaluation is made on a given expression to make a determination as to which case should be carried out.
  • The code block related to that case is performed if the expression matches a case constant.
  • In the event that a break is not implemented, the code will continue to traverse through each case until it either stumbles upon a break or exhausts all possibilities within the scope of its switch expression.
  • The section of code corresponding to the default case is run if none of the case constants match the value of the expression.

The break Keyword In Switch Case C++

In the event of encountering a switch while coding in C++, the break keyword is used within the said switch statement. This keyword functions as an exit strategy from any given case. In other words, it is used at the conclusion of each case block to ensure that the program control exits the loop when the matching case is processed. The cases following the matching case are all processed if the break keyword is absent.

This means that when the break statement appears, the switch statement is terminated. It is necessary to utilize a break statement in a switch to both halt the program and to free the memory. So we need to use the break keyword to end a series of statements, use the break keyword. Switch execution ends when the C++ compiler comes across a break keyword, and the control moves to the line that follows.

Example of a program without break keyword:

Output:

Inside Case 1
Inside Case 2
Inside Case 3
Inside Case 4
Inside Case 5
Inside the Default Case

Explanation

In the example above, we declare an integer variable choice and initiate it with the value of 1 inside the main function.

  • The switch statement then evaluates the choice variable's value against the case values.
  • Ideally, the code block related to case 1 is performed if the choice is equal to 1.
  • The fact that condition 1 does not contain a break statement means that every instruction within codes two through five, as well as the default, will execute.
  • As a result, the program will provide the following result if the value of the choice is 1.

Note: This program shows that a switch case can be written without a break statement. However, doing so is not advised. After a case is executed, the switch statement is terminated using the break statement. In the event that a break is omitted, the program shall repeatedly execute through each case until it encounters a case with an accompanying break statement or reaches the conclusion of its switch expression.

Example of the program using the break keyword:

Output:

Inside Case 1

Explanation:

  • We declare & initiate the integer variable choice, just like in the previous example.
  • And again, the variable's value is assessed using the switch C++ statement. The code block related to case 1 is performed if the choice is equal to 1.
  • After the code block related to case 1 has been executed, the switch statement is terminated using the break keyword, which was absent from the previous example.
  • As shown then, in the event that the break keyword is omitted, the program executes repeatedly through each case until it encounters a case with an accompanying break statement or reaches the conclusion of its switch expression.
  • Since we have the break keyword in the example, the program will provide the following result if the value of the choice is 1. And the cpp switch statement terminates after that.

The default Keyword In C++ Switch Case

The default keyword inside the body of switch statement in C++ designates a code to execute if the value of the expression and any of the case constants do not match. However, the default case is an optional statement that is only carried out if none of the case constants match the expression's value. 

If the expression's value does not align with any of the case constants, then what follows would be a colon indicating default conditions and execution of its corresponding code block. Meaning that the default case is used only if none of the case constants match the value of the expression. Also, if a default case is present in the switch block, it ought to be the switch statement's final case.

Example of switch case-default statement:

Output:

Inside the Default Case

Explanation:

  1. The program begins with the inclusion of iostream file.
  2. We then declare an integer variable called choice and initiate it with a value of 7 inside the main() function.
  3. The switch is then put to work, and the value of the variable choice is assessed against the case values inside the statement.
  4. Here, none of the case values match the value of the variable. This means that the code after the default case is executed and the statement terminates.  

Note: This example shows how in the event of no match between the expression and the program input, there exists a default keyword option with code for execution. The default case is optional and only runs if the value of the expression does not match any of the case constants.

Check this out- Boosting Career Opportunities For Engineers Through E-School Competitions

Switch Case Without Break And Default

In most programming languages, a switch statement allows you to execute different blocks of code based on the value of a variable. And the break statement is typically used within each case block to prevent fall-through. That is, once a case is matched, the execution falls through to the next case unless a break statement is encountered.

However, if you want to create a switch case without using break statements and a default case, you can achieve that by relying on the nature of fall-through behavior. Let's take a look at an example to see how this can be done. 

A program to show switch case without break and default:

Output:

The number is 2
The number is 3

Explanation:

In this example, we declare an integer variable called num and initialize it with the value of 2.

  1. We then initiate the switch body, where the variable value is compared against the case values. 
  2. There are three cases associated with the values 1, 2, and 3, respectively.
  3. After the comparison of num with these cases, the block of code corresponding to the second case is executed. Therein we use the cout statement to print the output.
  4. Since there is no break statement after case 2, so control moves on to the next case. As a result, the code will additionally run the case related to the value 3.

Note that since the switch statement lacks a default case, it is important to note that if num's value does not correspond with any of the cases, then said statement will essentially remain idle. And the program will proceed to the line of code after the switch statement.

Advantages & Disadvantages of C++ Switch Case

Listed below are the advantages of using the switch case in C++

  • The switch statements in C++ are more effective in comparison to the nested if-else statements.
  • It is a multiway branch statement that enables a variable to alter execution control, conditional upon it matching a case value.
  • It helps avoid repetitive coding and lessens the bulk while increasing the clarity of the program/ code.
  • It guarantees rapid execution and facilitates compiler optimization.
  • It is helpful in a program that uses menus and prints some menus on the screen.

Some of the disadvantages of using the switch decision-making statement are as follows:

  • As there are more constants to compare, the program becomes more difficult., making compilation difficult as well.
  • Unlike the organized switches found in contemporary languages like Pascal, the switch statement in C++ lacks organization.
  • Switch statements shouldn't be nested because it makes the program harder to read and more complicated.
  • A variable can only be compared to various integral values when using the switch statement.

Conclusion

In conclusion, the C++ switch statement is a multiway branch statement that enables choice between various code sections based on the value of an integral expression statement.

  • The switch case in C++ increases programming clarity and is more effective than nested if-else statements.
  • It guarantees faster code execution and simple compiler optimization.
  • The nesting of switch statements, though allowed, should be avoided as it makes the program control more complex and harder to read.
  • The complexity of the programming language, however, increases as the number of constants to compare does.

Also read- 51 C++ Interview Questions For Freshers & Experienced (With Answers)

Frequently Asked Questions

Q. Which statements are optional in the C++ switch?

There are two statements that are optional in the cpp switch case. These are:

  • The break statement: It is used in C++ switch case statements to end the switch block after a case has been executed. If a case does not contain a break statement, the control will pass to the following case and execute it as well.
  • The default statement: When none of the cases match the switch expression, the default case, which is optional, is run. The default statement always comes at the end of the switch case.

The break and default statements are optional in the switch case, per the C++ standard.

Q. What are the differences between switch and if else if ladder in C++?

The difference between the if-else-if ladder statement and the switch case statement is shown in the table below:

Switch Case

If-else-if Ladder

The switch statement is easier and cleaner to read and write.

If-else-if can become confusing if there are numerous conditions.

It is less flexible.

It is more flexible because it can handle complex conditions.

Switch statements are useful when you have several specific values to match.

If-else-if statements are better suited for more general tests and conditions.

Q. What is the C++ switch case?

The switch case in cpp is a replacement for the lengthy if statements that are used to compare a variable to several integral values. These statements have multiple branches. The switch statements enable any value to alter the execution's direction. They also allow for the optimum distribution of execution to various sections of the code.

The C++ switch statement syntax is as follows:

switch (expression) {
case value1:
// code to be executed if
// expression is equal to constant1;
break;
case value2:
// code to be executed if
// expression is equal to constant2;
break;
.....
.....
default code:
// code to be executed if
// expression doesn't match any constant
break;}

Q. What are break and default keywords in C++ switch cases?

The break keyword is used to break/ halter the execution of the switch block in C++. In other words, this keyword halts case testing inside the switch statement, and the program flow is passed on to the next line of code. 

When no case value matches, the default case specified by the default keyword will be applied. It is a non-mandatory statement meaning that the switch case statement will still function properly if this is skipped.

Q. What is meant by nested switch statements in C++?

Nested switch statements are those where one switch is included in the statement chain of another switch. It's possible that the constants for the inner and outer switches match.

Example of the nested switch statement:

Output:

Number 1 is 1
Number 2 is 2

Explanation:

Within the given code snippet, w declare two integer type variables named num1 and num2.

  • We then initiate a switch statement with another switch statement nested in it.
  • The outer switch case is comprised of num1, while the inner switch statement is num2.
  • The inner switch statement is carried out based on the value of num2 if num1 is equal to 1.
  • In the event that num2 holds a value of one, the case 1 statement shall be executed.
  • In contrast, if num2 is equal to 2, then the program executes the code of the second case statement.
  • Lastly, the default statement is carried out if num2 does not fit any of the conditions.
  • The case 2 statement is executed if num1 equals 2. The default statement is carried out if num1 does not fit any of the circumstances

The result that this particular program produces is Number 1 is 1 and Number 2 is 2. This is because num1 has a value of 1, meaning the first case statement is carried out. When num2 has a value of 2, the inner switch statement run, which causes the case 2 statement to be executed.

Q. Is the switch case a Boolean?

A switch case in C++ is not a boolean. A switch statement evaluates a given expression and then executes the statements connected to it based on the evaluated value. For each scenario, the value that is switched on is examined. Instead of being a Boolean expression, each case is a constant. Only types int or char may be used as the case value.

Q. Can you put a switch statement inside a switch statement in C++?

In C++, a switch statement can indeed be contained within another switch statement. This type of switch is called a nested statement. An outer switch statement's statement sequence may include the inner switch statement. However, if possible, one must avoid using nested switch statement since it complicates the program and make it difficult to read.

Q. Which type is not allowed in the switch case?

The permitted data types in switch case in C++ are:

  • Enumeration types (Enumerators are a sort of user-defined data that consists of a collection of named integral constants. The enum keyword defines enumeration types.)
  • Integral types: Char, short, int, long, and long long are the acceptable integral data types.
  • Switch statements are not permitted to use float or double, or other floating-point types.

The reason behind this is that there is difficulty in equating floating-point values that arises from their non-discrete nature. Non-enumeration user-defined types, like structs or class types, are not used in the switch case in C++ since they cannot be tested for equality.

You might also be interested in reading the following:

  1. References In C++ | Declare, Types, Properties & More (+Examples)
  2. Typedef In C++ | Syntax, Application & How To Use It (With Examples)
  3. Strings In C++ | Functions, How To Convert & More (With Examples)
  4. Pointers in C++ | A Roadmap To All Types Of Pointers With Examples
  5. Find In Strings C++ | Examples To Find Substrings, Character & More!
Shivani Goyal
Manager, Content

I am an economics graduate using my qualifications and life skills to observe & absorb what life has to offer. A strong believer in 'Don't die before you are dead' philosophy, at Unstop I am producing content that resonates and enables you to be #Unstoppable. When I don't have to be presentable for the job, I'd be elbow deep in paint/ pencil residue, immersed in a good read or socializing in the flesh.

TAGS
Engineering Computer Science
Updated On: 30 Apr'24, 09:53 PM IST