And what is the point of if-else statements if switch statements exist? Is there really a practical reason to have them both? It seems kinda redundant. What I'm trying to get at is, is one or the other essential for a certain scenario where the other just wouldn't work? And if so what is it.
Asked
Active
Viewed 79 times
0
-
everywhere a `switch` statement works, an `if` will work as well. I think the main reason is readability of your code. – Sirko Sep 06 '15 at 19:16
-
2http://stackoverflow.com/questions/680656/what-is-the-difference-between-if-else-and-switch probably duplicate question. – jewelhuq Sep 06 '15 at 19:23
-
http://stackoverflow.com/a/680664/4206206 – joe_young Sep 06 '15 at 19:30
1 Answers
0
Switch
statements can be thought of as a specialized if
statement. Anywhere that a switch
could be used an if
would also work; however, a switch
will usually be more readable.
Additionally, and more importantly in my opinion, is that in most compiled languages a switch will be faster than if/else because the compiler will generate a jump table. Because of that every possibility will have the same access time whereas in an if-else statement the last item in the list will take longer to reach than the first item. The performance benefit becomes more important the longer the list. That said, generally speaking, there are very few instances where the difference will be particularly noticeable or important.

TheGentleman
- 2,324
- 13
- 17
-
so basically its useful for specialized work loads? Also are there any conditions where only and only switch would work? I know that there are times that only if-else can work and switch can't i.e. booleans, but can it work the other way around? Does if-else fit in switch, switch fit in if-else or both? – Harsh Sep 06 '15 at 19:45
-
Yes, you can think of it that way. Most of the time that switch can be used it will be more readable than if-else and won't have much more of an impact. There is no place where switch will work that if-else won't. – TheGentleman Sep 08 '15 at 18:45