Is switch statement is alternate of if else staement ?
Is switch statement is alternate of if else staement ?
Collapse
X
-
I think every switch case can be replaced by every else if.
to newb16
Can you please give me an example that is not replaceableComment
-
-
-
The following if statements cannot be expressed by switch statements even if the arguments are integers.
Code:if ((a==2) && (b<c)) ... if (a==2) ... else if (b < c) ...
Comment
-
However one of the original purposes of the switch was to quickly and efficiently jump between multiple options. To this end switch statements often use to use jump tables where as switch statements processing the condition a single time where as if, else if ... else statements have to process multiple conditions.
In early compilers this had the effect of making switch more efficient than if, else if ... else, however I believe the advent of optimising compilers has tended to reduce this effect with the optimiser being able to choose the best way to implement both a switch and an if, else if ... else.Comment
-
Here are a few more reasons to NOT replace a switch statement with an if-elseif-else cascade:- It is less obvious to a maintainer that each leg of the if-elseif-else refers to the same variable than it is for a switch statement.
- You might mistakenly type the wrong variable name in one of the if-elseif expressions. This particular error is impossible with a switch statement.
- If the switch variable is an enumeration, some lint tools will warn you if any enumeration constants are not mentioned in the case statements.
Comment
-
Comment