The switch statement in c++
The program that we create should be readable. To increase the readability of the program we should use tools that is simple to read and understand. When possible use switch statement rather than if else statement, as it can be more readable than if else statement. But switch statement has limitation. It can't replace if else completely but can be helpful at certain situation. It can't do everything thing that if else statement can do. For example, switch statement can take only int or char datatype in c++. The following programs will help you to understand the switch statement.
/* A simple c++ program example that demonstrate the use of switch statement in c++ by taking character input.*/
// Program 1
#include <iostream>
using namespace std;
int main ()
{
char permit;
cout << "Are you sure you want to quit? (y/n) : ";
cin >> permit;
switch (permit)
{
case 'y' :
cout << "Hope to see you again!" << endl;
break;
case 'n' :
cout << "Welcome back!" < < endl;
break;
default:
cout << "What? I don't get it!" << endl;
}
return 0;
}
/* A c++ program example that demonstrate the use of switch statement in c++ by taking integer input. */
// Program 2
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
const int CHEESE_PIZZA = 11;
const int SPINACH_PIZZA = 13;
const int CHICKEN_PIZZA = 14;
cout << " *********** MENU ***********" << endl;
cout << setw (9) << "ITEM" << setw (20) << "PRICE" << endl;
cout << " (1) Cheese Pizza" << setw (8) << "$"
<< CHEESE_PIZZA << endl;
cout << " (2) Spinach Pizza" << setw (7) << "$"
<< SPINACH_PIZZA << endl;
cout << " (3) Chicken Pizza" << setw (7) << "$"
<< CHICKEN_PIZZA << endl;
cout << endl;
cout << "What do you want? ";
int option;
cin >> option;
cout << "How many? ";
int quantity;
cin >> quantity;
int price;
switch (option)
{
case 1:
price = CHEESE_PIZZA;
break;
case 2:
price = SPINACH_PIZZA;
break;
case 3:
price = CHICKEN_PIZZA;
break;
default:
cout << "Please select valid item from menu. " << endl;
return 1;
}
int amount = price * quantity;
cout << "Your Bill: $ " << amount << endl;
return 0;
}
Explanation for the above program:
In the above program we take an integer value from the user which is stored in 'option' variable. We pass this value to switch statement. The switch statement has 3 cases: case 1, case 2 and case 3. The case 1: is similar to if (option == 1). This is the advantage of switch statement over if else statement. You don't need to type the name of variable again and again if you are doing selection operation on same variable. You just put the variable name on switch statement and then just specify the value after 'case'. One more thing to be noted is that it requires 'break' statement at the end of each 'case'. If you remove the break statement then it will jump to the case that follows it. Try it and check by yourself. The 'default' is same as else in if else statement.