First, I realize that from a performance perspective, the design of this switch statement is slow because cout is being called several times in certain cases. That aside, is this style of writing a switch statement not good coding practice. In other words, would it be better to handle each case individually and break or is the fall-through better?
int main(void)
{
int number;
cout << "Enter a number between 1 and 10 and I will display its Roman numeral equivalent." << endl
<< "> ";
cin >> number;
cout << "Roman numeral: ";
switch (number)
{
case 3:
cout << "I";
case 2:
cout << "I";
case 1:
cout << "I";
break;
case 4:
cout << "I";
case 5:
cout << "V";
break;
case 6:
cout << "VI";
break;
case 7:
cout << "VII";
break;
case 8:
cout << "VIII";
break;
case 9:
cout << "I";
case 10:
cout << "X";
break;
default:
cout << "Error!\nYou did not enter a number between 1 and 10";
}
cout << endl;
return 0;
}
Switch statements aren’t slow, they’re usually optimised to jump-tables by the compiler. And if you’re sure that switch statement works as expected, it’s fine and is a pretty cool way of doing it.
That said, you’d have the same number of cases if you handled each one individually. If that’s all you’re doing, I’d probably change it to handle each one seperately and not do fall through. It’s more comprehendable and easily maintained that way:
And like @paxdiablo suggested, to enhance readability you can put the case, statement, and
breakall on the same line if it looks better to you: