Wednesday, June 20, 2007

if else Construct VS Switch Construct

Both the IF/IF ELSE  and switch statements are used to execute the pecific block of code depending upon the true condition. But both of them have their own pros & cons. Here are some I noticed.

A SWITCH STATEMENT IS BETTER WHEN
  • when you have more than two conditional expressions based on a single variable of numeric type/Character Type.
  • because it makes the code more structured, systematic and easy to understand.
  • In multiple if statements the conditions are to checked as many times the if statements are written where as in switch conditiion the condition is checked only once and jumps to required block.

AN IF/IF-ELSE STATEMENT IS BETTER WHEN
  • When you need to use the logical operators in CONDITION EXPRESSION, like you need to use && and || operators. Means your condition expression is not based on single variable.
  • Its not possible to use switch when our cases are floating points or strings.
DIFFERENCES
  1. In if-else construct: An expression is evaluated and the code is selected based on the truth value of the expression while in switch construct: An expression is evaluated and the code is selected based on the value of the expression.
  2. Each if has its own logical expression to be evaluated as true or false; while each case is referring back to the original value of the expression in the switch statement.
  3. The variables in the expression may evaluate to a value of any type, either an int or a char or an Object; while in switch construct the expression must evaluate to an int/char.
  4. There is one subtle but very important difference between the if-else-if ladder and the switch statement. That difference involves the break statement. In the if-else-if ladder, no matter what, only one of the blocks of code is executed. In the switch construct, if the break statement is omitted, the flow of execution will go forward into the next block. Leaving out a break is sometimes useful, but pretty rare. If you are missing a break statement in any block, make sure you intended to leave it out.

No comments: