Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use the switch statment instead of if else statments?

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?

like image 295
defectivehalt Avatar asked Feb 02 '10 15:02

defectivehalt


People also ask

Why do we use a switch instead of an if-else 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.

How are switch statements better than if-else statements?

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.

Should I use switch or if?

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.


1 Answers

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;
    }
like image 158
Yada Avatar answered Nov 16 '22 04:11

Yada