0
Which is easier Switch or if statement ?
6 Answers
+ 4
I think that switch statement is sometimes easier because it lets you perform the work of if statement like this
switch(num) {
case 13:
cout<<"Its thirteen"<<endl;
break;
}
but when you go to create a program where you need to take a range of integers like creating a age program (refer to my age guessing program)
then I think if statement works better although you go for a long coding. I still didn't understand how to command a range of int in switch but it is lot easier in if statement
So I think both if and switch statement are equally important
THANK YOU
+ 3
It depends on the program you write...when you want to give sevral values to a veriable you use switch but if you want to compare a variable with one value (if) is better but generally if statement is more common and useful.
+ 2
âď¸Advantages of switch over if-else ladder:
đšA switch statement works much faster than equivalent if-else ladder.
It is because compiler generates a jump table for a switch during compilation. Consequently, during execution, instead of checking which case is satisfied, it only decides which case has to be executed.
đšIt is more readable and in compare to if-else statements.
đšIt is more manageable for having higher level of indentation than if. For instance check below two source codes (solving same problem one using if where the other using switch) to check error messages.
âď¸Where to use switch over if-else ladder:
đšIf there are large number of compares for a condition in your program, use switch over if-else ladder.
đšFor more complex comparisons.
âď¸Where to use if-else ladder over switch:
In case of simple and few compares, if-else executes faster and easy write. Thus as per programâs requirement, a programmer should decide himself where to use which one condition control.
+ 1
switch is easier but not good than if
if is logical so it is tougher than switch
- 1
switch is lengthy but always useful
- 2
switch