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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Well,
switchfeels “lighter” in many cases than anif/else ifladder, in my opinion. Basically you don’t have that much syntax with braces and parentheses in the way of your code. That being said,switchinherits C’s syntax. That means you havebreakand only a single scope for variables unless you introduce new blocks.Still, the compiler is able to optimize
switchstatements 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 useswitchoverif/else ifif you’re dealing with numeric or enum types.