What is the difference between IF-ELSE and SWITCH?
They are pretty similar but each has a few special features.
switch
switchis usually more compact than lots of nestedif elseand therefore, more readable- If you omit the
breakbetween two switch cases, you can fall through to the next case in many C-like languages. Withif elseyou'd need agoto(which is not very nice to your readers ... if the language supportsgotoat all). - In most languages,
switchonly accepts primitive types as key and constants as cases. This means it can be optimized by the compiler using a jump table which is very fast. - It is not really clear how to format
switchcorrectly. Semantically, the cases are jump targets (like labels forgoto) which should be flush left. Things get worse when you have curly braces:case XXX: { } break;Or should the braces go into lines of their own? Should the closing brace go behind thebreak? How unreadable would that be? etc. - In many languages,
switchonly accepts only some data types.
if-else
ifallows complex expressions in the condition while switch wants a constant- You can't accidentally forget the
breakbetweenifs but you can forget theelse(especially during cut'n'paste) - it accepts all data types.
Comments
Post a Comment