#include <iostream>
usingnamespace std;
int main()
{
cout << "Select a Drink:\n";
int chosenDrink;
cout << "1. Coke\n2. Solo\n3. Fanta\n4. Lemonade\n5. Water\n";
cin >> chosenDrink;
switch (chosenDrink){
case 1:
cout << "Here's your Coke.";
break;
case 2:
cout << "Here's your Solo";
break;
case 3:
cout << "Here's your Fanta.";
break;
case 4:
cout << "Here's your Lemonade.";
break;
case 5:
cout << "Here's your Water.";
break;
default:
cout << "Error. choice was not valid, here is your money back.";
}
return 0;
}
When would you need to use else if instead of switch and switch instead of else if? Thanks.
Improved readability aside (when using switch statement), it is possible that the switch is more efficient because the compiler might generate a jump table (not guaranteed).
I'd generally prefer the switch statement for two reasons. Both the indentation and number of pairs of braces are usually cleaner and simpler. I've seen counter-arguments but on the whole I'd still prefer switch-case.
However, in the example code given, I'd prefer an array rather than a switch-case.
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
constint numDrinks = 5;
string drinks[numDrinks] = { "Coke", "Solo", "Fanta", "Lemonade", "Water"};
cout << "Select a Drink:\n";
for (int i=1; i<=numDrinks; i++)
cout << i << ". " << drinks[i-1] << endl;
int chosenDrink;
cin >> chosenDrink;
if (chosenDrink > 0 && chosenDrink <= numDrinks)
cout << "Here's your " << drinks[chosenDrink-1] << ".";
else
cout << "Error. choice was not valid, here is your money back.";
return 0;
}
The main advantage of this approach is not that the code is shorter. Rather it avoids repetition and automatically keeps the menu choices in line with the resulting output. If the list needed to be changed, it can be changed in just one place.