Sunday, 29 October 2017

Difference between if and switch in c

The switch statement is easy to edit because 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.

  1. Expression inside if statement decide whether to execute the statements inside if block or under else block. On the other hand, expression inside switch statement decide which case to execute.
  2. You can have multiple if statement for multiple choice of statements. In switch you only have one expression for the multiple choices.
  3. If-esle statement checks for equality as well as for logical expression . On the other hand, switch checks only for equality.
  4. The if statement evaluates integer, character, pointer or floating-point type or boolean type. On the other hand, switch statement evaluates only character or a integer datatype.
  5. Sequence of execution is like either statement under else block will execute or statements under if block statement will execute. On the other hand the expression in switch statement decide which case to execute and if you do not apply a break statement after each case it will execute till the end of switch statement.
  6. It is difficult to edit if else statements as it is tedious to trace where the correction is required. On the other hand, It’s easy to edit switch statements as they are easy to trace.
  7. If expression   turn outs to be false, statement inside else block will be executed. If expression inside switch statement turn out to be false then default statements is executed.

No comments:

Post a Comment