Other Language Constructs - switch case
Published by
sanya sanya
The "switch-case" statement is a control flow statement used for multi-way branching. It provides a way to select one of many possible execution paths based on different cases or values of a variable or an expression.
Syntax:
switch (expression) {
case value1:
// Code block to be executed if expression matches value1
break;
case value2:
// Code block to be executed if expression matches value2
break;
// more case statements...
default:
// Code block to be executed if expression doesn't match any case
}
Example:
#include
using namespace std;
int main() {
int choice;
cout << "Menu:\n";
cout << "1. Option 1\n";
cout << "2. Option 2\n";
cout << "3. Option 3\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "You selected Option 1.\n";
break;
case 2:
cout << "You selected Option 2.\n";
break;
case 3:
cout << "You selected Option 3.\n";
break;
default:
cout << "Invalid choice.\n";
}
return 0;
}
Output:
Menu:
1. Option 1
2. Option 2
3. Option 3
Enter your choice: 2
You selected Option 2.
Applications of a switch statement:
1. Menu-driven programs: It is commonly used to implement menu-based user interfaces where different actions are performed based on the user's choice.
2. Handling multiple conditions: It provides an alternative to using multiple if-else statements when there are several distinct cases to consider.
3. Language compilers: Switch statements are often used in compilers to generate code based on the tokens or keywords encountered.
Advantages of a switch statement:
1. It enhances code readability by providing a concise way to handle multiple cases.
2. It improves code maintainability by grouping related cases together.
3. It can be more efficient than a series of if-else statements, especially when there are many cases, as the expression is evaluated only once.
Disadvantages of a switch statement:
1. It can only be used with certain data types (integer, character, enumeration) and not with floating-point numbers or strings.
2. It doesn't support range-based matching, so you can't check if a value falls within a specific range using a switch statement.
3. Nested switch statements can make code more complex and harder to understand.
Library
WEB DEVELOPMENT
FAANG QUESTIONS