nested if Vs switch statements

BASIS FOR COMPARISONIF-ELSESWITCH
BasicWhich statement will be executed depend upon the output of the expression inside if statement.Which statement will be executed is decided by user.
Expressionif-else statement uses multiple statement for multiple choices.switch statement uses single expression for multiple choices.
Testingif-else statement test for equality as well as for logical expression.switch statement test only for equality.
Evaluationif statement evaluates integer, character, pointer or floating-point type or boolean type.switch statement evaluates only character or integer value.
Sequence of ExecutionEither 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 ExecutionIf 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.
EditingIt 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.
Exampleif (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