Switches seem so useless as they can be replaced with if-else statements, which can do much more than just match a char/int/enum etc. I can only think of one good use for a switch, and that would be for interpreting command line args.
What are some realistic uses for a switch statement?
A switch statement is usually more efficient than a set of nested ifs. Deciding whether to use if-then-else statements or a switch statement is based on readability and the expression that the statement is testing.
An if-else statement can evaluate almost all the types of data such as integer, floating-point, character, pointer, or Boolean. A switch statement can evaluate either an integer or a character. In the case of 'if-else' statement, either the 'if' block or the 'else' block will be executed based on the condition.
Use switch every time you have more than 2 conditions on a single variable, take weekdays for example, if you have a different action for every weekday you should use a switch. Other situations (multiple variables or complex if clauses you should Ifs, but there isn't a rule on where to use each.
There are a few cases where switch is more readable and comes in handy. Usually when you have grouping of options.
Here is one of them:
int numDays = 0;
int month = 2;
int year = 2010;
// find the number of days in the month
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
numDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
numDays = 30;
break;
case 2:
if ( ((year % 4 == 0) && !(year % 100 == 0))
|| (year % 400 == 0) )
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println("Invalid month.");
break;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With