+ 2
Rather than the syntax what is the difference in use of if else statement and switch case?
2 Answers
+ 1
There is difference between ladder if else and switch.
Limitations of switch over ladder if-else
1. The variable expression are not allowed in cases.
Eg. case i+1:
2. Can not test flat expression using switch.
Eg. Switch(x>y)
3. Switch statement must know value inside it during compilation.
4. Can't use for complex comparison.
5. For simple and few expression better to go for ladder if-else because of fast execution and easy to write.
Advantage of Switch:
1. Switch work faster than equivalent ladder if-else.
2. More readable compare to ladder if-else.
3. Management is easy.
4. If large number of compare then go for switch.
- 1
You can always translate a switch statement to a chain of if/else, but the opposite is not always true.