difference between if and switch

This is a discussion on difference between if and switch within the C Programming forums, part of the General Programming Boards category; hi, what is the exact difference between if else and swich............? we can do, what ever we want by using ...

  1. #1
    Registered User
    Join Date
    Jul 2009
    Posts
    5

    difference between if and switch

    hi,

    what is the exact difference between if else and swich............?

    we can do, what ever we want by using if else instead of switch. Then when we should use switch instead of if.

    Thanks,
    Munish

  2. #2
    Banned ಠ_ಠ's Avatar
    Join Date
    Mar 2009
    Posts
    687
    switch statements are faster than if else statements but can only simulate == and else operations, they cannot compare two variables

    for example.
    Code:
    if (foo == 1) 
    else if (foo == 2)
    else if (foo == 3)
    .
    .
    .
    else
    Code:
    switch (foo)
      case 1:
      case 2:
      case 3:
      .
      .
      .
      default:
    with the if-else if-else all of the conditions need to be checked until a correct one is found (O(n) worst case), the switch statement uses a jump table so it doesn't need to check making it O(1)
    Last edited by ಠ_ಠ; 07-12-2009 at 01:19 AM.
    ╔╗╔══╦╗
    ║║║╔╗║║
    ║╚╣╚╝║╚╗
    ╚═╩══╩═╝

  3. #3
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You can also do fall through with a switch.


    Quzah.
    Hope is the first step on the road to disappointment.

  4. #4
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,302
    Did you also know that you can put a case statement anywhere you like, inside a switch statement, and have it jump into there?
    You can't do things such as "Duff's Device" with if-statements!

    I shall now point towards which is more maintainable:
    Take the example shown above. We now decide we wish to test against (foo+bar), although we do not wish to modify the value of foo. Which one makes this change easy?
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  5. #5
    Registered User
    Join Date
    Jun 2005
    Posts
    6,266
    Quote Originally Posted by iMalc View Post
    You can't do things such as "Duff's Device" with if-statements!
    LOL .... haven't seen that one for years. Duff's device is an optimisation, which relies on specific details of how compilers usually map switch/case to machine code.

    Apart from the "trip up novice maintainers" benefit, there are also examples where Duff's device has been shown to result in inefficient code - IIRC because it interferes with pipelining and branch prediction with some processor architectures.
    Right 98% of the time, and don't care about the other 3%.

  6. #6
    Registered User
    Join Date
    Jul 2009
    Posts
    40
    the switch statement uses a jump table so it doesn't need to check making it O(1)
    It doesn't need to check the cases is that what you mean? If we remove break it's going to execute the succeeding statement to the next case does that prove that it's not checking the cases?

    Code:
    switch( gender )
    {
         case 'M': 
                          //male
                          break;
         case 'F': 
                         //female
                         break;
         default: 
                         //invalid input
    }

  7. #7
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Quote Originally Posted by WatchTower View Post
    It doesn't need to check the cases is that what you mean? If we remove break it's going to execute the succeeding statement to the next case does that prove that it's not checking the cases?

    Code:
    switch( gender )
    {
         case 'M': 
                          //male
                          break;
         case 'F': 
                         //female
                         break;
         default: 
                         //invalid input
    }
    A switch is, at bottom, a computed goto. A series of if-else if-else if-else requires each condition to be checked; a switch does not.

  8. #8
    Registered User
    Join Date
    Oct 2008
    Posts
    1,262
    Quote Originally Posted by ಠ_ಠ View Post
    with the if-else if-else all of the conditions need to be checked until a correct one is found (O(n) worst case), the switch statement uses a jump table so it doesn't need to check making it O(1)
    The switch statement MAY use a jump table so it MAY make it O(1).

    It really depends on the circumstances. If you only have a few cases with all low values then yes, your compiler - if it's good - is quite likely to use lookup tables. If you have many huge values your compiler may decide to use something like a binary search to make it O(log n). Or your compiler might decide to check all cases making it O(n). Or your compiler may decide to check all cases n times, making it O(n*n). Although that's quite unlikely.

  9. #9
    Registered User
    Join Date
    Jul 2009
    Posts
    40
    Quote Originally Posted by tabstop View Post
    A switch is, at bottom, a computed goto.
    ok, so I understand that it switch doesn't have to check any condition. What do you mean at bottom? computed goto?

    I was just curious what is the : switch( gender ) <- isn't this a condition? How is it able to check if you type in the correct input like if you press 'M' it should display male? does it have to check the cases( which are the gotos I presumed)? If break is removed from case 'M': it will display female as well, how come? doesn't it know how to check which is right or wrong without the break statement?

    Code:
    switch( gender )
    {
         case 'M': 
                          //male
                          break;
         case 'F': 
                         //female
                         break;
         default: 
                         //invalid input
    }

  10. #10
    Registered User
    Join Date
    Oct 2008
    Posts
    1,262
    Quote Originally Posted by WatchTower View Post
    I was just curious what is the : switch( gender ) <- isn't this a condition? How is it able to check if you type in the correct input like if you press 'M' it should display male? does it have to check the cases( which are the gotos I presumed)? If break is removed from case 'M': it will display female as well, how come? doesn't it know how to check which is right or wrong without the break statement?
    That is actually done on purpose because it's quite useful. It runs the content of the conditions until a break occurs (well, or returns, continue for a loop, goto, etc). For instance, let's say we want condition 5 through 1 done for 5, 4 through 1 for 4, 3 through 1 for 3, etc. This is quite common and easy enough:
    Code:
    switch(num) {
      case 5:
        // Only for 5
      case 4:
        // For 4 and 5
    }
    etc

  11. #11
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Quote Originally Posted by WatchTower View Post
    ok, so I understand that it switch doesn't have to check any condition. What do you mean at bottom? computed goto?

    I was just curious what is the : switch( gender ) <- isn't this a condition? How is it able to check if you type in the correct input like if you press 'M' it should display male? does it have to check the cases( which are the gotos I presumed)? If break is removed from case 'M': it will display female as well, how come? doesn't it know how to check which is right or wrong without the break statement?

    Code:
    switch( gender )
    {
         case 'M': 
                          //male
                          break;
         case 'F': 
                         //female
                         break;
         default: 
                         //invalid input
    }
    "At bottom" is an English phrase that means roughly "with all the extras stripped away". As to the efficiency, imagine you have case 1 through case 100 (heaven help us). If you did if-else if-else if-...-else you would have to make 100 comparisons to get to the end, because each condition will be checked. In a switch, your compiler may just make a table of the 100 locations in code where the cases are, and then just look up the appropriate value when necessary, so only one comparison/look-up is required rather than 100.

  12. #12
    Registered User
    Join Date
    Jul 2009
    Posts
    40
    I see, I understand now.

Popular pages Recent additions subscribe to a feed

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21