#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;
}
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.
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.