+ 3
which is better in switch and if else if
8 Respuestas
+ 9
If/else if has more uses, but if you are in a situation where you can use either of the two, use switch. That way, people trying to understand your code (including future you) won't have to check all the if conditions and check whether they relate to the same thing or not.
+ 5
If else if is a better option because :
If else if can evaluate multiple conditions whereas switch evaluates only 1 I.e equality
If else if is more versatile as it can handle range too
Switch cannot handle floating point tests whereas if else if can
+ 4
if else is better because u can easily do it without any harrase plus it is simple to remember
+ 2
depends upon the case
+ 1
Switch can check whether a variable is EQUAL to a value only.
e.g.
switch(x)
{
case 1: cout <<"Hey"; break ;
case 2:cout <<"Hello";break;
default :cout <<"Hi";
}
Here , we cannot check whether the value of x is HIGHER or LOWER than to a value we give. We can only check whether the value of x is EQUAL to a value we give.
Tell me if this example has problems. :D
+ 1
It depends on the number of conditions or choices are there. If there are less number of choices or conditions then u can use any one of them and when you are not confirm about the particular choice number which displays your required result.
Switch is better when there are more number of choices and when you are sure about which choice number or condition will display your required result because if the program is in if/else if form to display the result last of condition's result then the JVM takes more time in executing the program as it shld check for all above conditions.. If we use switch den we can directly we can display last choice's result.
0
switch is easy at used in simple exception .. if else more useful at hard exception
0
if else if