Thread: Switch/case vs if/else

  1. #1
    Math wizard
    Join Date
    Dec 2006
    Location
    USA
    Posts
    582

    Switch/case vs if/else

    There are 2 sets of key words that can potentially do the same thing - switch/case and if/else. Question is, which is the better method to use for something like this?

    Code:
    unsigned int CaseID;
    
    ...
    
    // compare this
    switch(CaseID)
    {
       case 1:
          // do stuff if the "CaseID" variable is 1
          break;
       case 2:
          // do stuff if the "CaseID" variable is 2
          break;
       default:
          // do stuff if the "CaseID" variable is anything else
    }
    
    // to this
    if (CaseID == 1)
    {
       // do stuff if the "CaseID" variable is 1
    }
    
    else if (CaseID == 2)
    {
       // do stuff if the "CaseID" variable is 2
    }
    
    else
    {
       // do stuff if the "CaseID" variable is anything else
    }
    Both methods accomplish exactly the same effect so what is the difference? Performance (aka faster to process)? Readability? Something else?
    High elevation is the best elevation. The higher, the better the view!
    My computer: XP Pro SP3, 3.4 GHz i7-2600K CPU (OC'd to 4 GHz), 4 GB DDR3 RAM, X-Fi Platinum sound, GeForce 460, 1920x1440 resolution, 1250 GB HDD space, Visual C++ 2008 Express

  2. #2
    Registered User rogster001's Avatar
    Join Date
    Aug 2006
    Location
    Liverpool UK
    Posts
    1,472
    there is much debate and has been much discussion about if else versus switch, none of it conclusive. in my opinion a switch is nearly always preferable once you get to 4 or even 3 if else statements and beyond, its just much clearer, even though if else is quite easy to read, a switch to me is just a nicer structure to look at.
    If your cases are all nicely consecutive then a switch (I read) will more than likely be consolidated to a jump table at compile time. I also read You cannot include conditional test as case labels for this reason.
    Last edited by rogster001; 09-17-2010 at 09:43 AM.
    Thought for the day:
    "Are you sure your sanity chip is fully screwed in sir?" (Kryten)
    FLTK: "The most fun you can have with your clothes on."

    Stroustrup:
    "If I had thought of it and had some marketing sense every computer and just about any gadget would have had a little 'C++ Inside' sticker on it'"

  3. #3
    Math wizard
    Join Date
    Dec 2006
    Location
    USA
    Posts
    582
    What's a jump table?

    I usually prefer if/else over switch/case because, to me, if/else reads better as it reads more like plain English. "If ID number equals exactly 1, test equals 1" is much easier to read due to better English correctness than "case ID number 1, test equals 1". Of course, that's just my opinion. Whether 50 items are listed or just 2, I otherwise have a strong preference toward using if/else and, recalling switch/case, I was wondering if I should be using switch/case instead of if else for series like explained in my initial post, especially for the menus where it wouldn't be unusual to see numerous options listed, some with submenus (which means nested switch/case), others with nothing more than a function call and they're generally sequential.
    High elevation is the best elevation. The higher, the better the view!
    My computer: XP Pro SP3, 3.4 GHz i7-2600K CPU (OC'd to 4 GHz), 4 GB DDR3 RAM, X-Fi Platinum sound, GeForce 460, 1920x1440 resolution, 1250 GB HDD space, Visual C++ 2008 Express

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by ulillillia
    What's a jump table?
    It might be a good idea to search the Web concerning this.

    Quote Originally Posted by ulillillia
    I usually prefer if/else over switch/case because, to me, if/else reads better as it reads more like plain English.
    You have a point there, but then the condition of an if statement can be just about any boolean expression, whereas a switch is more specific, i.e., some integral value is being compared with a series of integral values. I think that this can actually make one's intention more explicit, as in your example of menu options.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    Registered User rogster001's Avatar
    Join Date
    Aug 2006
    Location
    Liverpool UK
    Posts
    1,472
    as in your example of menu options.
    Exactly, it just provides that little layer of abstraction to visualise whats is happening and intended,

    some integral value is being compared with a series of integral values
    This again supports comprehension, if you read a line that says switch(verticies) and you know you are working on a fractal program then that places the following cases perfectly into context, and your mind naturally sees it, if you are following a stack of logic statements, albeit on the same theme, and even if they are clear, then reading down a tree going 'if this is not that, then, unless if this is not that, then, unless...sure its english but i think its translation into the switch is more succinct and elegant.
    Last edited by rogster001; 09-17-2010 at 09:45 AM.
    Thought for the day:
    "Are you sure your sanity chip is fully screwed in sir?" (Kryten)
    FLTK: "The most fun you can have with your clothes on."

    Stroustrup:
    "If I had thought of it and had some marketing sense every computer and just about any gadget would have had a little 'C++ Inside' sticker on it'"

  6. #6
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    My rule is:
    When working with known constants... use Switch.
    When having to resolve conditional statements... use else if...

    Code:
    switch (barq)
       { case 1 :
           ......
          case 99 :
          default  : }
    
    if (x+ y < 31)
       ....
    else if (x + y >5097)
       ....
    else if (x - y ==31)
       ....
    else
       return;
    I believe switch is a bit faster because of the simplicity of the comparisons, but the two methods do output very similar code.

  7. #7
    Banal internet user
    Join Date
    Aug 2002
    Posts
    1,380
    Quote Originally Posted by ulillillia View Post
    There are 2 sets of key words that can potentially do the same thing - switch/case and if/else. Question is, which is the better method to use for something like this?

    Both methods accomplish exactly the same effect so what is the difference? Performance (aka faster to process)? Readability? Something else?
    Readability and debugability (is that even a word?) are rather subjective but some people (including me) find the switch statement to be more clear. However, in many cases a compiler has a better chance of generating faster code using a switch compared to the if/else construct. But the performance gains might be moot if you're using them for a menu system, as menus aren't exactly performance-critical pieces of a program.

  8. #8
    Third Eye Babkockdood's Avatar
    Join Date
    Apr 2010
    Posts
    352
    I've always preferred if-else over switch-case. Mostly because it's easier to read and more compact.

  9. #9
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    I fail to see how if/else is more compact.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  10. #10
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Knowing that a compiler may use a jump table or even a binary search for a switch statement isn't necessary.

    It is enough to simply realise that with an if/else-if chain, you're telling the compiler exactly in which order to check these things, and it must do as you asked. There is very little room for the compiler to work its own optimisation magic.
    With a swtich however, the compiler is free to make sure that it arrives at the correct case by any means necessary. It can do tests in any order it likes, or compute any kind of jump table it likes, or use profile guided optimisation to put the more common cases first, as long as it gives the right end result. So there is far more room for compiler optimisation to kick in.

    It's about telling the compiler what you want, any letting it work out the how, rather than telling it the how directly.
    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"

  11. #11
    Third Eye Babkockdood's Avatar
    Join Date
    Apr 2010
    Posts
    352
    Quote Originally Posted by Elysia View Post
    I fail to see how if/else is more compact.
    Code:
    #include <stdio.h>
    
    int main() {
        int x = 8, y;
        printf("Enter the magic number: ");
        scanf("%d", &y);
        if (y == x) printf("Correct.\n");
        else printf("Incorrect.\n");
        return 0;
    }
    Code:
    #include <stdio.h>
    
    int main() {
        int x = 8, y;
        printf("Enter the magic number: ");
        scanf("%d", &y);
        switch (y) {
            case 8:
                printf("Correct.\n");
                break;
            default:
                printf("Incorrect.\n");
                break;
        }
        return 0;
    }
    One man's trash is another man's treasure.

  12. #12
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Code:
        switch (y)
        {
            case 8: printf("Correct.\n"); break;
            default: printf("Incorrect.\n"); break;
        }
    2 vs 5 lines. Add more than one statement per if and the difference is negligible.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  13. #13
    Third Eye Babkockdood's Avatar
    Join Date
    Apr 2010
    Posts
    352
    Quote Originally Posted by Elysia View Post
    Code:
        switch (y)
        {
            case 8: printf("Correct.\n"); break;
            default: printf("Incorrect.\n"); break;
        }
    2 vs 5 lines. Add more than one statement per if and the difference is negligible.
    You can put as many statements as you want on one line.

    Code:
    if (!argv[1]) printf("There are no arguments.\n"); return 1;
    else printf("There is at least one argument.\n"); return 0;
    EDIT: Ah, you got me there. I still prefer if/else.
    Last edited by Babkockdood; 09-18-2010 at 04:13 PM.

  14. #14
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    You cannot, because that's a compile error.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  15. #15
    Third Eye Babkockdood's Avatar
    Join Date
    Apr 2010
    Posts
    352
    Yeah, I realized that. Look at the edit.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. problem with cin.fail() in if/else clause
    By clearcom in forum C++ Programming
    Replies: 1
    Last Post: 04-17-2010, 10:11 PM
  2. can you place a if/else statement in a switch case
    By swansea in forum C++ Programming
    Replies: 4
    Last Post: 02-27-2010, 08:59 PM
  3. Need help with if/else and switch commands please
    By masterofwar14 in forum C++ Programming
    Replies: 4
    Last Post: 09-29-2009, 12:28 AM
  4. Issues with using CHAR with IF/ELSE conditions.
    By TheBlackVeil in forum C++ Programming
    Replies: 5
    Last Post: 07-31-2007, 10:58 AM
  5. If/else statement not working
    By zenovy in forum C++ Programming
    Replies: 1
    Last Post: 01-18-2006, 08:26 PM

Tags for this Thread