When choose if-else over switch? | Sololearn: Learn to code for FREE!

+3

When choose if-else over switch?

Can anyone tell me which one is effective to use?

11/29/2016 4:47:05 AM

Vaibhav Dwivedi

7 Answers

New Answer

+10

There are some rules of good coding. Better practice is to use Switch over ledder of if-else. It is less complicated to manage and reading.

+3

Of course you can use, but execution time is greater than switch statement. Assume the case, all you if, else if conditions are failed and your else block is executing. In this case, your pgm executes all if and else if conditions. If you use switch statement here, then control directly goes to corresponding case and it won't check all other cases.

+3

switch is used when an *EXACT* response is used.. example: switch (choice) { case "A": // do a code break; case "B": // do b code break; case "C": //do "C" code break; } if /else if/else statements are used with more ambiguous variables: if (a < 100){ //do code} else if (a<200){ // do code} else { //do code}

+2

Say for eg, if you're having less number of conditions then go head for if-else (means not more than 2 else if statement) otherwise choose the switch statement. Also in few languages like c++ only support the enums, int in switch cases. It don't support the strings in case. So in those cases no other go we have to choose if-else statements. Hope you understand this

+2

@venki, I get your point but for more than 2 statement, cannot I just use ladder if- else? then again, why choose switch?

+1

if there is choices based problems then switch statement is good at that type of places and if you want to generate a problem through a conditions then if..else statement is good at that place...

+1

Case 1:When you have variable controlled program you must have to use switch but if your program is based on multiple conditions you must have to use if else ladder. Case 2:If you have less statements use if else otherwise use switch statements