and why can all switch statements be written as if statements?
Four answers:
anonymous
2011-01-29 14:28:22 UTC
1) If you see the assembly listing produced by the compiler, you can realize that a switch statement is more compact and efficient than a series of if statements.
2) switch enables better indentation of code, if you have the habit of beautifying the code, so more readable source.
.
Light Cloud
2011-01-29 14:26:00 UTC
In many languages, switch statements only allow certain data types. For instance, in Java, you can put ints in the switch statement, but not strings, or other comparisons.
However, it is true that every switch statement can be re-written as an if statement.
Similarly, for loops and do-while loops can all be rewritten as just while loops. Switch statements are sometimes syntactically simpler and/or make the logic easier to see.
Also, in many languages, compilers convert switch statements into a jump table ( http://en.wikipedia.org/wiki/Branch_table ). However, there's really nothing stopping a compiler from optimizing the corresponding if-else statements the same way.
tbshmkr
2011-01-29 14:43:28 UTC
No real reason.
=
Switch is an form of the if-else ladder..
-
no1home2day
2011-01-29 14:23:23 UTC
Because they said so.
Your question lacks sufficient details. I would ask, in response, "Why NOT?"
ⓘ
This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.