Switch vs If...else statement

Status
Not open for further replies.

Thunder

Wise, Aged Ars Veteran
108
I am in my first C++ programming classes, and I was wondering what the difference between a Switch with cases is and if..else statement.

For example the programming we are doing has to do with mileage and reinbursment. Can I do calculations for milage and money in a switch statement, or is it better to do it in an if..else statement.

i was thinking along the lines of

If (j=>2001)
{
.12*2000+175
else if (j>3000)
{
.10*3200+190
... Until the end.
 

Midlands

Ars Praetorian
535
Subscriptor
My take is that switch(...) was introduced for two reasons:

- Readability, and
- Being able to compile it to an indexed table of branch addresses.

I suspect that the second one was actually the primary motivator, because the switch/break construct is notoriously easy to abuse (by cascading cases accidentally, among others).

These days, it's not remotely clear that doing the second one would even be a good idea, except for a few special cases (where your target selection is very, very dense -- probably only useful in generated lexers, for example). Modern CPUs will throw fits at this since it jacks their branch-prediction algorithms.

I'd just as soon have a 'switch' statement that takes a generic set of test cases and branches to the first one it matches -- not just for integers, for example. This would probably increase the readability greatly in certain cases (especially where comparing a string against a number of literals), and be compilable to the same thing as a set of if-else's.
 

splicer

Ars Tribunus Militum
2,135
Originally posted by Midlands:
My take is that switch(...) was introduced for two reasons:

- Readability, and
- Being able to compile it to an indexed table of branch addresses.

I suspect that the second one was actually the primary motivator, because the switch/break construct is notoriously easy to abuse (by cascading cases accidentally, among others).

These days, it's not remotely clear that doing the second one would even be a good idea, except for a few special cases (where your target selection is very, very dense -- probably only useful in generated lexers, for example). Modern CPUs will throw fits at this since it jacks their branch-prediction algorithms.

Midlands, all modern compilers do generate tables when the circumstances are right (large amount of switch 'arms' which are fairly dense). The other two methods generally used are sequential compares and a binary-tree like structure for large switches that are fairly sparse.

You are correct that branch predictors will not do well on this kind of indirect branch. However keep in mind that the worst that can happen is a single mispredict. You can do far worse with the other two techniques.
 

Pont

Ars Legatus Legionis
26,160
Subscriptor
Switch statements can be easier to read than if/else statements.

Switch statements always compare to a single value, with an "else" or "default" block at the end. A programmer reading the code can easily just read the case statements and know what valid data is. With long if/elseif blocks, you can start with the functional equivalent of a switch statement, but some programmer along the way throws in a > or < in the mix. Suddenly, it just became a lot harder to mentally follow the boolean logic in the if/elseif blocks.

Switch statements aren't necessary. They're just a convenient tool for structuring your code. Probably one step above the ternary operator (since Switch statements are actually readable).
 

jbode

Ars Legatus Legionis
11,752
Subscriptor
Originally posted by Thunder:
I am in my first C++ programming classes, and I was wondering what the difference between a Switch with cases is and if..else statement.

You use a switch statement when you want to branch based on a small set of integral values. You use an if-else statement when you want to branch based on anything else.

If-else statements are more flexible than switches, but sometimes switches make things simpler.

For example the programming we are doing has to do with mileage and reinbursment. Can I do calculations for milage and money in a switch statement, or is it better to do it in an if..else statement.

i was thinking along the lines of

If (j=>2001)
{
.12*2000+175
else if (j>3000)
{
.10*3200+190
... Until the end.

Right idea, but your implementation has a bug. Set j to 5000 and step through it manually and you'll see what I mean.

Here are two ways to implement the above logic with a switch. I think you'll see why the if-else statement works best for this kind of stuff:

code:<HR>
Code:
/* 
** Option 1 
*/
switch (j > 3000)
{
    case 0: /* false */
        switch ( j >= 2001)
        {
            case 0: /* false */
                x = 0;
                break;
  
            case 1: /* true */
                x = .12 * 2000 + 175;
                break;
        }
        break;

    case 1: /* true */
        x = .10 * 3200 + 190;
        break;
}

/*
** Option 2
*/
switch (j)
{
    case 2001:
    case 2002:
    case 2003:
    ...
    case 2999:
    case 3000:
        x = .12 * 2000 + 175;
        break;

    case 3001:
    case 3002:
    ...
        x = .10 * 3200 + 190;
        break;
    
    ...
}

Yuck, right?
 
I've always wondered, when a switched is converted to machine code, does it end up the same as the corresponding if/elseif/else code?

Major differences between switch and if/elseif: "if" can have complex expression with multiple variables, You can have statements in your "else if"s that change your variables' states and really confuse the programmer who replaces you, And "switch" statements can fall through to the next case.
 

newton_meter

Ars Scholae Palatinae
1,424
Originally posted by splicer:
Quick answer is 'sometimes' See my post above.

And the longer answer is 'sometimes'.

The Scheme R5RS standard defines "case" (which is more general that C/C++/Java flavored switch) as syntactic sugar for nested "if"'s. On the other hand, the Haskell '98 standard defines "if" as syntactic sugar for a "case" (which is again more general than C/C++/Java's switch) that dispatches on a boolean value.

In (some implementations of) those languages, it may well be the case that every if or case compiles to the "equivalent" code in terms of the other.

However, C and C++ programmers have this expectation that every source language program corresponds precisely with an assembly language equivalent. In fact, they often take the semantics of a language construct to be "that which it is translated to by the compiler". In other words, they write certain things with the expectation that they will be translated in a certain way.

Compiler writers don't spend a lot of effort violating this assumption unless there's a big win :)

(kg*m*m)/(s*s)
 
Status
Not open for further replies.