In C++, the switch statement serves as a control flow mechanism that allows the execution of different code blocks depending on the value of a specified expression. It provides a more advanced and efficient alternative to using a series of if-else-if statements for making choices among multiple options.
The C++ switch statement runs a single statement based on various conditions. Its structure resembles the if-else-if ladder statement in C++.
Syntax
It has the following syntax:
switch(expression){
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break;
......
default:
//code to be executed
break;
}
In this syntax,
- Switch: It is the keyword for the statement.
- Expression: It represents the value against every case value is evaluated.
- Default: If none of the classes are matched, the default case is executed.
- Break: The break keyword is utilized to break the statement after the matching case has been executed.
Flowchart of the Switch Statement in C++
As illustrated in the flow diagram, apply the subsequent procedures to incorporate the switch statement in C++:
In the initial step, the switch statement is assessed for its value.
Next, the determined case value is compared with the existing case values to find a match.
In this step, the program checks the value of the case. If the value matches a case, the corresponding block of code is run. If there is no match, the default case block is executed.
Step 4: Subsequently, if a break statement is encountered within the block, the program control will exit the switch statement following the execution of that specific case. In the absence of a break statement within the block, execution will continue with all subsequent cases after the matching case.
Finally, the commands are carried out following the switch statement.
C++ Switch Example
Let's consider a basic example to demonstrate the switch statement in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
int main () //main function
{
int num;
cout<<"Enter a number to check grade:";
cin>>num;
switch (num) //Switch statement
{
case 10: cout<<"It is 10"; break; //case 1
case 20: cout<<"It is 20"; break; //case 2
case 30: cout<<"It is 30"; break; //case 3
default: cout<<"Not 10, 20 or 30"; //prints the default value
break;
}
}
Output:
Enter a number:
10
It is 10
Output:
Enter a number:
55
Not 10, 20 or 30
Calculator Program using Switch Statement in C++
Let's explore another example where we develop a calculator program in C++ by utilizing the switch statement.
Example
#include <iostream>
using namespace std; //using standard namespace
int main() //main function
{
float num1, num2;
char oper;
cout << "Choose any operator (+, -, *, /): " <<endl;
cin >> oper;
cout << "Enter the Number 1: ";
cin >> num1;
cout << "Enter the Number 2: ";
cin >> num2;
switch (oper) //switch statement
{
case '+': //case 1 addition
cout << num1 << " + " << num2 << " = " << num1 + num2;
break;
case '-': //case 2 subtraction
cout << num1 << " - " << num2 << " = " << num1 - num2;
break;
case '*': //case 3 multiplication C++
cout << num1 << " * " << num2 << " = " << num1 * num2;
break;
case '/': //case 4 division
cout << num1 << " / " << num2 << " = " << num1 / num2;
break;
default: //default case
//if any operator doesn't match any given case
cout << "Error! Choosen operator is not correct" <<endl;
break;
}
return 0;
}
Output:
Choose any operator (+, -, *, /):
*
Enter the Number 1: 15
Enter the Number 2: 4
15 * 4 = 60
Rules of the Switch Statement in C++
Several rules of the switch statement are utilized in C++. Some of them are as follows:
- In C++ switch statement, the case value of the program must be either char or int type.
- It does not allow duplicate case value in C++.
- It can have several number of cases.
- Every case statement can have a break statement. It is an optional in switch statement.
- The case labels should be followed by a colon ":".
- The default statement of the switch statement is also an optional.
Nested Switch Case in C++
In C++, when a switch case is placed inside another switch case, it is referred to as a nested switch case. This structure allows for making decisions at multiple levels depending on various conditions.
Syntax:
It has the following syntax:
switch (expression1) {
case value1:
switch (expression2) {
case valueA:
// Code for inner switch
break;
case valueB:
// Code for inner switch
break;
}
break;
case value2:
// Code for outer switch
break;
default:
// Default case for outer switch
}
C++ Nested Switch Case Example:
Let's consider a scenario to demonstrate the nested switch statement in C++.
Example
#include <iostream>
using namespace std;
int main()
{
//choose branch from C - Computer Science, E - Electrical, M - Mechanical
char branch = 'M';
int collegeYear;
cout<<"Enter the College Year: ";
cin >> collegeYear;
switch( collegeYear ) //switch statement
{
case 1: //case 1
cout<<"English, Maths, Science";
break;
case 2: //case 2
switch( branch ) //switch statement
{
case 'C':
cout<<"Operating System, Java, Data Structure";
break;
case 'E':
cout<<"Control Systems, Digial Electronics, Electronic Engineering";
break;
case 'M':
cout<<"Fluid Mechanics, Thermodynamics, Computer-aided design";
break;
}
break;
case 3: //case 3
switch( branch ) //switch statement
{
case 'C':
cout<<"C, C#, JavaScript";
break;
case 'E':
cout<<"Power Electronics, Power Systems, Circuit Theory";
break;
case 'M':
cout<<"Mechatronics, Energy Conversion and Power Plants";
break;
}
break;
case 4: //case 4
switch( branch ) //switch statement
{
case 'C':
cout <<"C++, Python, Machine Learning";
break;
case 'E':
cout<<"Analog Electronics, Electrical Machines";
break;
case 'M':
cout<<"Aerodynamics, Materials Science, Engineering Graphics and CAD";
break;
}
break;
default: //default statement
cout<<"Error: Choose the correct year."; //print the default value
}
}
Output:
Enter the College Year: 4
C++, Python, Machine Learning
C++ Switch Statement fall-through
In C++, the fall-through behavior of the switch statement can result in unforeseen outcomes and subtle bugs. This situation arises when the program flows from one case block to the next without a clear break statement. Essentially, when a case is matched, all following case blocks will be executed until a break statement is reached.
C++ Switch Statement fall-through Example:
Let's consider an example to demonstrate the fall-through behavior of the switch statement in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
int main() //main function
{
int val; //assign integer value
cout <<"Enter the Number: "; //input value
cin >> val;
switch (val) //switch statement
{
case 1:
cout << "C" << endl;
// No break statement, will fallthrough
case 2:
cout << "C++" << endl;
// No break statement, will fallthrough
case 3:
cout << "C#" << endl;
break;
default:
cout << "Other" << endl;
}
return 0;
}
Output:
Enter the Number: 1
C
C++
C#
Features of Switch Statement
Several features of the switch statement in C++ are as follows:
- In C++, the switch statement is easy to read and implement than the if-else
- It makes easy to maintain and debug the program, which improves the execution performance.
- In C++, the depth of the switch statement is fixed. It enables to the optimized implementation for faster code execution.
- The switch statement is used to compare the value of a variable with several other values.
Limitations of Switch Statement
Several limitations of switch statement in C++ are as follows:
- In C++, the switch statement cannot be utilized directly with string variables and expression.
- In switch statement, variables or expressions cannot be utilized as case labels because each case label must reflect a constant value that is known at compile-time.
- It cannot handle complex case conditions or expressions.
- It cannot directly compare non-integral types.
- It cannot be utilized with the Goto and jump statements.
Conclusion
In summary, the C++ switch statement provides a versatile mechanism that simplifies the management of different scenarios within programs. With clear case labels and concise syntax, it enhances code readability and upkeep, particularly in scenarios with numerous potential results. This statement enhances the structuring of program logic by establishing a straightforward connection between cases and corresponding actions.
The switch statement offers performance benefits compared to an if-else-if ladder as it allows for compiler optimization, resulting in faster execution. It is important for developers to understand the limitations of switch statements, including the requirement for integral or enumeration expression types and constant case values.
C++ Switch Case MCQs:
- Which of the following operator is utilized after the case keyword in C++ Switch Statement?
- Semicolon (;)
- Colon (:)
- Comma (,)
- Dot (.)
- Which of the following option is true for switch statement in C++?
- Default case is optional in C++ switch statement.
- It is compulsory to include at least one case value in the switch case.
- There is no limitation on the number of cases that may be include in as switch statement.
- None of the above.
- What is the use of default case in C++ switch statement?
- It is used to terminate the switch statement.
- It is used to execute code when any of the case values does not match.
- It used to specify the first case to be executed.
- It is utilized to declare a variable.
- What is the main purpose of a switch statement in C++?
- Is used to declare a variable.
- Is used to define a function.
- Is used to execute a code block repeatedly.
- Is used to choose one of multiple code blocks to execute based on the value expression.
- Which of the following option is not a valid case label in a C++ switch statement?
- case 2:
- case 'b':
- case 2.7:
- case 800: