views:

2356

answers:

6

Can someone please explain this to me?

A: 

this shows the differences for c. If you want more please specify your question. What programming language are you talking about? What do you mean by difference? Timing? Codestyle? Usage?

theomega
+9  A: 

They are pretty similar but each has a few special features.

switch

  • switch is usually more compact than lots of nested if else and therefore, more readable
  • If you omit the break between two switch cases, you can fall through to the next case in many C-like languages. With if else you'd need a goto (which is not very nice to your readers ... if the language supports goto at all).
  • In most languages, switch only accepts primitive types as key and constants as cases. This means it can be optimized by the compiler using a jump table which is very fast.
  • It is not really clear how to format switch correctly. Semantically, the cases are jump targets (like labels for goto) which should be flush left. Things get worse when you have curly braces:

    case XXX: {
    } break;
    

    Or should the braces go into lines of their own? Should the closing brace go behind the break? How unreadable would that be? etc.

if-else

  • if allows complex expressions in the condition while switch wants a constant
  • You can't accidentally forget the break between ifs but you can forget the else (especially during cut'n'paste)
Aaron Digulla
One note to mention that the case fall through behaviour is language spcific, c will happily allow you do do this but c# places some restrictions on falling through one case statement to another.
TK
A: 

We really need to know what language you're talking about to be accurate in our responses. In general they do the same thing, and most of the time you pick the one that is most readable for your context. But that may not hold true across different languages and different situations, so we need more info.

Charlie Flowers
+3  A: 
Zaagmans
Not quite an exact duplicate though. The one you link to is specifically asking about fall-through and using OR in the if-else statement.
lc
A: 

in C#, Switch expects a constant value if you need to compare with the value of a variable, you will have to use if-else

Natrium
A: 

i think that main difference is that in if-else blocks we can test conditions.but does not go exactly in same way in switch

sandeep