switch
statements are for speed. That's why they are only numeric. The compiler will attempt to make a lookup table for non-sparse (i.e. contiguous) value ranges which can improve performance significantly when the code is constantly being executed. This is because it only needs to do 1 comparison for a contiguous range to determine what piece of code to execute.
switch
statements potentially can cause hard to find bugs since at the end of each case
you need to specify a break
or the execution will fall through to the next case
.
if
/else if
/else
statements are for more general use. They are in general, slower than an equivalent switch
statement if there are many comparisons against the same value. However if that if
chain of statements is not executed a lot and the chain is not that long, the performance improvement is negligible.
For more general usage, if
is the way to go. In a CYOAG, you will not be needing speed. The slowest part of the game is the user.
To explain this to a 13 year old:
If you think that you will be executing a comparison on a single
integer (whole number) value over 1,000,000 or more times all at once and you need
it to be done as quickly as possible, use a switch
statement.
Otherwise, doesn't matter. Just be careful when using a switch
, because if you
don't have a break
at the end of each case
you will be scratching you head
trying to figure out what just happend? when two or more case
s are executed.