Thursday, December 3, 2009

Differeence between switch and nested if ,else statement

Typically, nested if-else statements are used in the program's logic where there isn't only one condition to evaluate. A switch statement, on the other hand, evaluates only one variable and starts to work there. You can think of a switch statement as a simplified (and stripped-down) version of an if-else block.

switch(x) {
case 1: // do this
case 2: // do this
case 3: // do this
// etc
}

The nested if-else statement's power comes from the fact that it is able to evaluate more than one condition at once, and/or use lots of different conditions in one logical structure.

if(x == 0) {
// do this
} else if(y == 1) {
// do this
} else if(x == 1 && y == 0) {
// do this
}

If you're going to evaluate only one variable in the condition statement, you're better off going with a switch statement, since it looks a lot neater than nested ifs. However, like in the case above, there are times where the only structure you could use is an if-else block, so you don't have much of a choice.