Between switch and if statements

When to use if statements and when to switch statements and why? When is it optimal to use each of them (i don’t mean together, i mean since they are similar, why should i use one and not the other)?

A switch statement is what we call “syntactic sugar” for a series of if/else statements. What that means is that under the covers it gets converted to an if/else statement. It just exists to make certain logic easier to read and write. So the answer to you question is that you should use a switch statement when it makes you code more clear.

To be a bit more specific, we tend to use switch statements in cases where we know that a value could be one of a set of possibilities and we have a specific action we want to take for each of those.


This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.