34

Can someone please explain this to me?

tsilb
  • 7,977
  • 13
  • 71
  • 98
  • Just a pointer - you won't get many helpful responses if you don't take the time to properly phrase the question. – J M Mar 25 '09 at 08:19
  • Never mind :) it's been done. – J M Mar 25 '09 at 08:19
  • There's already a question about this on SO: [Switch vs if-else](http://stackoverflow.com/questions/97987/switch-vs-if-else) **[EDIT]**
    As "lc" stated in a comment to this answer, the above question is not a duplicate, but it still might give you a good idea of the workings and what to use if that specific situation occurs.
    – RuudKok Mar 25 '09 at 08:22
  • 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. Mar 25 '09 at 08:30

7 Answers7

38

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.

  • In many languages, switch only accepts only some data types.

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)
  • it accepts all data types.
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
  • 1
    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. Mar 25 '09 at 08:29
  • one of the major difference is the way they check the condition - with `if-else` you can only check for equality, whereas with `switch` you can do a bit more.. – Mahendra Liya Sep 25 '12 at 12:55
8

The main difference is that switch despatches immediately to the case concerned, typically via an indexed jump, rather than having to evaluate all the conditions that would be required in an if-else chain, which means that code at the end of the chain is reached more slowly than code at the beginning.

That in turn imposes some restrictions on the switch statement that the if-else chain doesn't have: it can't handle all datatypes, and all the case values have to be constant.

user207421
  • 305,947
  • 44
  • 307
  • 483
5

IF else - IT is used for taking a decisions

Switch statement - It is used to test the value of the given variable against a list of case value .

gustavohenke
  • 40,997
  • 14
  • 121
  • 129
Kv mathew
  • 59
  • 1
  • 1
  • Both are used for testing values, and both are used for taking decisions. You can't take a decision without testing a value, and testing a value is pointless unless you are going to take a decision. – user207421 Sep 10 '21 at 00:23
3

Differences Between if-else and switch

  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. If-esle statement checks for equality as well as for logical expression . On the other hand, switch checks only for equality.

  3. 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.

  4. Sequence of execution is like either statement under if block will execute or statements under else 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.

  5. If expression inside if 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.

  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 is easy to edit switch statements as they are easy to trace.

in one word we can say switch acts a little bit faster than if else statement!!!

amdev
  • 6,703
  • 6
  • 42
  • 64
MD RAHIIM
  • 99
  • 1
  • 10
  • "If expression inside switch statement turn out to be false then default statements is executed": this is not the case. Consider `boolean b = false; switch (b) { case true: break; case false: break; }`. No `default` there. – user207421 Jun 04 '21 at 07:39
  • And (1) is a distinction without a difference. `if` decides whether to execute the if-statement or the else-statement. `switch` decides which case to execute. There is no essentiall difference here. – user207421 Sep 10 '21 at 00:25
1

The difference between Switch and if-else statement is below:

This is the general syntax of if-else ladder:

if (condition1) { //Body of if }
    else if (condition2) { //Body of if }
    else if (condition3) { //Body of if }
else { //default if all conditions return false }

And this is the general syntax for switch:

switch ( variable )
{
 case <variable value1>: //Do Something
                                             break;
 case <variable value2>://Do Something
                                             break;
 default: //Do Something
                break;
}

The if-else ladder is of type strict condition check, while switch is of type jump value catching.

Advantages of switch over if-else ladder:

  • A switch statement works much faster than equivalent if-else ladder. It is because compiler generates a jump table for a switch during compilation. Consequently, during execution, instead of checking which case is satisfied, it only decides which case has to be executed.
  • It is more readable and in compare to if-else statements.
Chilll007
  • 612
  • 1
  • 5
  • 20
Rizwan Shaikh
  • 273
  • 3
  • 8
0

A Clear difference:

  • The if...else statement checks whether the conditions in the parenthesis evaluates to true or false
  • The switch statement checks if the equality of the value in the parenthesis against the value of the case keyword evaluates to true.

Example

var a  = 'hello'

Example - if...else

if(a == 'hello') {
  print('right!')
} else if (a == 'hi')
  print('left!')
} else {
  print('wrong!')
}

Example - Switch

switch(a) {
  case 'hello': // a == 'hello'
    print('right!')
    break // You should add this
  case 'hi': // a == 'hi'
    print('left!')
    break
  default: // this executes if no equality was met in the values above.
    print('wrong!')
}

// If you are not sure of either of the parenthesis value or the
// case value or you want to make more complex conditioning, you can use `true`:

var age = 18:
switch(true) {
  case age < "18": // 18 < 18 == false
    print("under age!");
    break;
  case age == 18: // 18 == 18 == true
    print("right age!");
    break;
  default:
    print("18+!");
}
Erisan Olasheni
  • 2,395
  • 17
  • 20
-3

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