What is the difference between if else and switch case? | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
+ 1

What is the difference between if else and switch case?

please help.

17th Jun 2017, 8:16 PM
Aniruddha Nath Sarma
Aniruddha Nath Sarma - avatar
3 ответов
+ 2
If you're just using a single comparison for the conditional for each if-else if, and you have multiple else if clauses then a switch is probably the way to go. However, if you are only using 1 or maybe 2 else if clauses then I would probably just use it. Likewise if you're using multiple comparisons in your conditionals then you may need to stick with an if-else if clause. This could easily be a switch: if (x > 6) //code else if ( x < 4) //code else if ( x == 5) //code else if (x != 5) //code else //default code This might be better as an if-else if: if (x > 6 || y > 6 && isNumber()) //code else if ( x < 4 || y < 4 && isPositiveNumber()) //code else if ( x == 5 || y == 5) //code else if (x != 5 && x != 5) //code else //default code
17th Jun 2017, 8:55 PM
ChaoticDawg
ChaoticDawg - avatar
+ 3
Basically they have no difference. but the use of them does: "if else" comes after "if" statement so you're kinda saying you want the first statement to be true. if it isn't, then check another condition and so on. Switch is faster and better understandable in long term and bigger condition checks.
17th Jun 2017, 8:40 PM
Mat
Mat - avatar
+ 1
I have a tip for you, switch on an enum to make your code even more readable.
17th Jun 2017, 8:51 PM
Tim