switch
statement
The switch statement is used to select one of many code blocks to be executed. Very similar to if-else statements.
I don’t use these much.
Example
What is the
default
keyword?The
default
keyword specifies some code to run if there is no case match
BE CAREFUL, if you forget the break
, then the statement will continue running.
For example,
When should you use
switch
overif ... else
?If a switch contains more than five items, it’s implemented using a lookup table or a hash list.
Therefore, if you are comparing against constant values, the
switch
syntax is likely preferable, since you can compare in time rather than in time for anif...else
statement.