Switch vs If/ElseIf/Else | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 7

Switch vs If/ElseIf/Else

what is the difference of using the switch statements or if/else statements? they both kinda do the same thing...how do I choose which one to use? are there pros and cons for using each?

6th Jul 2017, 2:03 AM
MCJEH - avatar
5 Answers
+ 11
not much difference but switch statement is faster than if else because for if else statement all the cases have to be checked which should be executed instead in switch statement it only decide which should be executed.
6th Jul 2017, 2:08 AM
Samira - avatar
+ 5
Almost every post here claimed that switch statement is faster then if. Does anyone here have a solid proof code sample that can prove switch statement is faster then if?.
12th Jul 2017, 4:21 AM
+ 3
Switch only accepts concrete values as cases of the variable being tested, while if-elseIf-else allows a more flexible test with comparison signs and because of that, can cover wider or complex cases.
6th Jul 2017, 10:11 PM
José Ruiz
José Ruiz - avatar
+ 1
switch case is less code intensive and makes for faster processing of the information.
7th Jul 2017, 9:07 PM
James Barrow
James Barrow - avatar
+ 1
Internally, machine code doesn't have an instruction similar to SWITCH on high level languages. The unique programmatic structure is a comparison with CMP and a conditional jump with JMP/JPZ/JPE or other, what is completely equivalent to a high level IF. SO compilers translate directly IF to machine code and SWITCH has to be firstly translated to a battery of IF's. Therefore, SWITCH IS NOT MORE QUICK THAN SWITCH. The only reason to use SWITCH is when you don't have complex cases of conditions to manage in order for you to have simplicity in code.
9th Jul 2017, 10:50 AM
José Ruiz
José Ruiz - avatar