+ 4
If "switch" is more efficient why do we need to use if else all that?
16 Answers
+ 7
Switch is faster in some situations, if statements in others. Additionally, using an if statement is the only way to check whether a variable has a value at all e.g. if(x == null){ //do stuff } else { //do other stuff } this check helps avoids issues were 99% of the time the variable should have a value but there's a 1% chance it doesn't.
If statements also let you define the order in which you want to check the condition. So, if you know that 85% of the time a condition is going to be true (x < 10) then you will stick that at the top, the next condition might be true 10% of the time, so that goes second, third and fourth might be 3% and 1% respectively.
+ 5
Because of the different 'if' ways 'switch' does not support operation inexact comparison (> < ≥ ≤) and can only take integer values as arguments (char is also an integer type), it takes only simple values. In fact, the switch does not know how to compare it, it takes on input an integer and using jump-tables, like goto, is moved to the corresponding label in the code. Due to this it is significantly faster than a simple if.
+ 2
Switch itself is a application of if and else if's. If takes conditions which must result boolean, thus it can be used to give more complex conditions
+ 2
else if is more handy when you have to check 1 thing. When you wannacheck lots of things, better use the switch statement
+ 2
as we do nesting of if loops for multiple condition this cannot be done in switch case
+ 2
You can't use switch in comparisons
e.g.
if(x>5)
can't be written in switch case
Also, you cant take any variable in the case expression.
e.g.
int x=5;
switch(){
...//some code
case x: // gives error
+ 1
if your output depends upon separate conditions then you have to use if then else if, and if you have only one condition for all outputs then you can use switch is better
+ 1
when you wants to compare something like x<18 or. like y>10 you have to use if else statement.
+ 1
морковь
+ 1
good question and very helpful answers
0
even though you can do caseless switch statements to acieve x < 5 i.e.
switch (x)
case 1:
case 2:
case 3:
case 4:
{
// code for x < 5
}
break;
0
Wait @Aoron Coad you could do all that with a switch statement, just saw if this condition is true then do this and if its not (!==)do this, I mean it is basically an else statement just w/o the else
- 1
If you have only one condition, then you go for switch statement but when you have more conditions no option than to go for if, if else
- 1
when there is many situation than we used the switch
- 2
xxx