I appreciate that anything that can be done by a switch statment, can be done by an if else statement.
But are there stylistic rules for when one should use the switch rather than if else statment.
Switch statements are cleaner syntax over a complex or stacked series of if else statements. Use switch instead of if when: You are comparing multiple possible conditions of an expression and the expression itself is non-trivial. You have multiple values that may require the same code.
The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type.
Use switch every time you have more than 2 conditions on a single variable, take weekdays for example, if you have a different action for every weekday you should use a switch. Other situations (multiple variables or complex if clauses you should Ifs, but there isn't a rule on where to use each.
The switch statement has a fixed depth. It allows the best-optimized implementation for faster code execution than the “if-else if” statement. It is easy to debug and maintain the programs using switch statements. The switch statement has faster execution power.
Well, switch
feels "lighter" in many cases than an if
/else if
ladder, in my opinion. Basically you don't have that much syntax with braces and parentheses in the way of your code. That being said, switch
inherits C's syntax. That means you have break
and only a single scope for variables unless you introduce new blocks.
Still, the compiler is able to optimize switch
statements into a lookup table and perform compile-time checking for literals when dealing with enumerations. So, I'd suggest that it's usually preferable to use switch
over if
/else if
if you're dealing with numeric or enum types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With