I’m not sure I understand the difference between an if block and switch/select block.
I mean I use them all the time. But It’s not clear to me when the switch block should be applied and when no to. Since, a select block can be expanded into if block.
So the only real advantage I can think of for using the select block is for human readability.
I’m not sure I understand the difference between an if block and switch/select block.
Share
The answer will vary a bit depending on the language. For instance, in C and C++,
switch(select) statements can get turned into fairly efficient jump tables by the compiler, partially because they’re more restrictive thanifstatement conditions. (Although to be fair modern compilers are pretty darned good at optimizing all sorts of stuff.) This may not be true of all languages/compilers (I seem to recall VB6 basically treatedSelect Caseas a series ofIf/ElseIfstatements.)Readability is definitely a factor: Using a
switch(orSelect Casein VB) tells anyone following you that all of the branches below branch on a common condition, which is quite useful.Maintainability (related to, but different from, readability) is a factor as well. If you change the one thing being branched on in a
switch, you’re done; if you have a long series ofifstatements, it’s easy to miss one (or more) out.