1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Rep Power

    Are switch statements pointless?

    I don't know, but I just see them as if and elseif statements that can only take conditions involving number values. What makes them better than if and elseif statements?
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Rep Power
    To some extent it is related to the compiler and the way it optimizes the code. For limited set of decision statements, switch/case could be better from a performance point of view (not necessarily always)
  4. #3
  5. Contributing User

    Join Date
    Aug 2003
    Rep Power
    An if/else if/else chain is indeed more flexible in that each condition expression may be different and more complex. Therein lies your answer - a switch is much simpler and more constrained so can be optimised more easily by the compiler. The simplest possible construct that achieves the desired results will be much more efficient, and easier to maintain.

    Try writing a large switch statement and a corresponding if/else if/else chain and compare the generated code in your debugger or compiler assembler output. Certainly where the case labels are contiguous range of integers, the compiler will generate a jump-table for the switch and go directly from the switch to the case, whereas in an if/else-if/else chain each condition in the chain will be tested in turn until the correct one is found. Even sparse and out-of-order case values are likley to generate simpler code that the equivalent if/else-if/else code.
  6. #4
  7. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Woodland Hills, Los Angeles County, California, USA
    Rep Power
    IN early UNIX code you'll see some instances of switch...case which use the default fallthrough feature (admittedly, this feature isn't used very much though in most code).
    switch (value) {
        case 23:
        case 15:
        case 32:
        case 47:
    Here, if the value is 15, it will run do_more_stuff() and jump out because of the break below it. If value is 23, it will run do_something() and then fall through and run do_some_more_stuff() because there is no break in between case 23 and case 15. In most of our programming situations, people put break in between two case statements, but in the early UNIX kernel code, there were some situations where they used the fall-through feature.

    Also if the value is 32 or 47, it will run do_other_stuff();
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo

IMN logo majestic logo threadwatch logo seochat tools logo