Selection Statement – Switch Statement
Selection statements in C++ are used to control the flow of a program. They allow you to execute different blocks of code based on different conditions.
The two main selection statements in C++ are:
- if statement: The
if
statement allows you to execute a block of code if a condition is true. - switch statement: The
switch
statement allows you to select one of multiple blocks of code based on the value of an expression.
We explained “if statement” in “Selection Statement – if Statement” section, and now we are going to explain more about “switch statement”.
The switch statement in C++ is a control statement that allows you to execute different blocks of code based on the value of an expression. The general syntax of a switch statement is as follows:
switch (expression) { case value1: // code to execute if expression equals value1 case value2: // code to execute if expression equals value2 ... default: // code to execute if expression does not equal any of the values in the case statements }
The expression
can be any integer expression. The switch statement evaluates the expression
and compares it to the values of the case
statements. If the expression
equals one of the values in the case
statements, the code block inside that case
statement is executed. If the expression
does not equal any of the values in the case
statements, the code block inside the default
statement is executed.
Here is an example of a switch statement:
#include <iostream> using namespace std; int main() { int x = 0; cin >> x; switch (x) { case 1: cout << "case #1" << endl; break; case 2: cout << "case #2" << endl; break; case 3: cout << "case #3" << endl; break; default: cout << "Out of range" << endl; break; } return 0; }
You can also use characters instead of numbers in switch statement. For Example:
#include <iostream> using namespace std; int main() { char c = 'a'; switch (c) { case 'a': cout << "case #a" << endl; break; case 'b': cout << "case #b" << endl; break; default: cout << "Out of range" << endl; break; } return 0; }
Output will be:
case #a
Remember!
Using a capital letter like ‘A’ in the previous example is not like using a small letter like ‘a’. They are not the same!
Benefits of using switch statements
Switch statements can be more efficient than using a series of if statements, especially when there are many different cases. Switch statements can also make your code more readable and maintainable.
Conclusion
Switch statements are a powerful tool for controlling the flow of your C++ program. By understanding how to use them, you can write more efficient and reliable code.