BASIS FOR COMPARISON | IF-ELSE | SWITCH |
---|---|---|
Basic | Which statement will be executed depend upon the output of the expression inside if statement. | Which statement will be executed is decided by user. |
Expression | if-else statement uses multiple statement for multiple choices. | switch statement uses single expression for multiple choices. |
Testing | if-else statement test for equality as well as for logical expression. | switch statement test only for equality. |
Evaluation | if statement evaluates integer, character, pointer or floating-point type or boolean type. | switch statement evaluates only character or integer value. |
Sequence of Execution | Either if statement will be executed or else statement is executed. | switch statement execute one case after another till a break statement is appeared or the end of switch statement is reached. |
Default Execution | If the condition inside if statements is false, then by default the else statement is executed if created. | If the condition inside switch statements does not match with any of cases, for that instance the default statements is executed if created. |
Editing | It is difficult to edit the if-else statement, if the nested if-else statement is used. | It is easy to edit switch cases as, they are recognized easily. |
Example | if (expression) { Block of statements; } else if(expression) { Block of statements; } . . else { Block of statements; } | switch( expression ){ case constant1: statement(s); break; case constant2: statement(s); break; case constant3: statement(s); break; . . default statement(s); } |
The switch statement is easy to edit as it has created the separate cases for different statements whereas, in nested if-else statements it become difficult to identify the statements to be edited.
No comments:
Post a Comment