When choose if-else over switch? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

When choose if-else over switch?

Can anyone tell me which one is effective to use?

29th Nov 2016, 4:47 AM
Vaibhav Dwivedi
Vaibhav Dwivedi - avatar
6 Answers
+ 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.
29th Nov 2016, 5:23 AM
Chill
+ 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.
29th Nov 2016, 5:20 AM
Venkatesh(Venki)
Venkatesh(Venki) - avatar
+ 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
29th Nov 2016, 5:13 AM
Venkatesh(Venki)
Venkatesh(Venki) - avatar
+ 2
@venki, I get your point but for more than 2 statement, cannot I just use ladder if- else? then again, why choose switch?
29th Nov 2016, 5:14 AM
Vaibhav Dwivedi
Vaibhav Dwivedi - avatar
+ 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...
29th Nov 2016, 7:36 AM
Rohan Yadav
Rohan Yadav - avatar
+ 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
29th Nov 2016, 6:13 PM
Gamer
Gamer - avatar