Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use If-else if-else over switch statements and vice versa [duplicate]

Why you would want to use a switch block over a series of if statements?

switch statements seem to do the same thing but take longer to type.

like image 390
K2J Avatar asked Jan 09 '09 11:01

K2J


People also ask

When should you use a switch case instead of ELSE IF statements?

The if-else statement is used to choose between two options, but the switch case statement is used to choose between numerous options. If the condition inside the if block is false, the statement inside the else block is executed.

Which is the most applicable to use between if if-else and switch case why?

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.

What is the advantage of switch statement over if-else statement?

Advantages of C++ Switch Statement The switch statement has a fixed depth. It allows the best-optimized implementation for faster code execution than the “if-else if” statement. It is easy to debug and maintain the programs using switch statements. The switch statement has faster execution power.

Which is faster switch or if-else?

Most would consider the switch statement in this code to be more readable than the if-else statement. As it turns out, the switch statement is faster in most cases when compared to if-else , but significantly faster only when the number of conditions is large.


2 Answers

As with most things you should pick which to use based on the context and what is conceptually the correct way to go. A switch is really saying "pick one of these based on this variables value" but an if statement is just a series of boolean checks.

As an example, if you were doing:

int value = // some value if (value == 1) {     doThis(); } else if (value == 2) {     doThat(); } else {     doTheOther(); } 

This would be much better represented as a switch as it then makes it immediately obviously that the choice of action is occurring based on the value of "value" and not some arbitrary test.

Also, if you find yourself writing switches and if-elses and using an OO language you should be considering getting rid of them and using polymorphism to achieve the same result if possible.

Finally, regarding switch taking longer to type, I can't remember who said it but I did once read someone ask "is your typing speed really the thing that affects how quickly you code?" (paraphrased)

like image 83
tddmonkey Avatar answered Oct 12 '22 13:10

tddmonkey


If you are switching on the value of a single variable then I'd use a switch every time, it's what the construct was made for.

Otherwise, stick with multiple if-else statements.

like image 32
Garry Shutler Avatar answered Oct 12 '22 12:10

Garry Shutler