given to a switch must be an int
or a defined type that resolves to an int (long int might work too, it's been awhile). The reason for this is that a switch compiles
into a jump table
. This is important because finding what you're looking for in a jump table would take O(1) time instead of the O(n) time (where n is the number of conditionals) it could take to check every conditional
if you were to implement this as a series of if()/elseif() statements.
It's also worth pointing out that you'll probably want to put a "break
;" at the end of every block of code after a condition. If you don't your code will go to the correct condition
and then execute all the code after that, including code intended for other conditions. Of course this may be what you want. See Duff's Device
has brought it to my attention that a switch doesn't always compile to a jump table. This caused me to drag out my copy of the Dragon Book
. On pages 497-498 it says that if there are less than 10 values or so you can implement it as "a sequence of conditional goto's." If there are more than 10 use a hash table
. However, no matter how many values you have, if they are reasonably contiguous
use a jump table.
Of course depending on your compiler
and your optimization