Thread: Switch Case Question

  1. #1
    Registered User
    Join Date
    Apr 2006
    Posts
    38

    Switch Case Question

    I was doing the quiz on this website dealing with Switch Case and I have a question. Question 4 states

    Code:
    4. What is the result of the following code?
    
    x=0;
    
    switch(x)
    
    {
    
      case 1: cout<<"One";
    
      case 0: cout<<"Zero";
    
      case 2: cout<<"Hello World";
    
    }
    
    A. One
    B. Zero
    C. Hello World
    D. ZeroHello World
    The answer is D. Why is it D? I understand there is no break statement but for it to execute case 2 the value of x would need to be 2 but its 0. Why is Hello World getting outtputted when the case value is not met?

  2. #2
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    switch statements "fall through"; that is, the code keeps executing until a break statement [edit=2] or the end of the switch [/edit] is reached. The case label only indicates where the code starts executing when the case value is met.

    So because there isn't a break for case 0, the execution "falls through" and the code for case 2 is executed as well.

    [edit]
    To see the fall-though effect, try this program:
    Code:
    #include <iostream>
    
    using std::cout;
    using std::endl;
    
    int main(void) {
        for(int x = 0; x < 3; x ++) {
            switch(x) {
            case 0: cout << "zero" << endl;
            case 1: cout << "one" << endl;
            case 2: cout << "two" << endl;
            }
    
            cout << endl;
        }
    }
    [/edit]
    Last edited by dwks; 06-05-2006 at 04:23 PM.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  3. #3
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    > Why is Hello World getting outtputted when the case value is not met?

    Because of the way the case statements are arranged: since there is no break in the example, x will make the switch jump to the code at case 0, and it keeps running until all cases after that are accounted for.

  4. #4
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446
    a switch statement execution begins at the case label that evaluates the condition to true and ends at the end of the switch statement or when a break statement is found.

    Consider it this way; once the proper case label is found, no more case labels will be tested. Everything between there and the end of the switch statement will be executed unless you use a break.

    Some people find switch statements odd because they "force" them to use the break statement repeatedly. This couldn't be further from the truth. Sometimes the desirable effect is exactly to have the code process across all case labels, starting at the one that evaluates to true.

    Code:
    int stage = 3;
    switch (stage) {
        case 1:
            fixMotherboardToCase();
        case 2:
            fixGrahicsToMotherboard();
        case 3:
            fixHardDriveToCase();
        case 4:
            fixPowerToCase();
            connectHardDriveToPower();
        case 5:
            PaintLogoOnCase();
        default:
            Ship();
    }
    And even more powerful is the notion that you can have both worlds, by having switch statements with break statements on some labels and not on others.
    Last edited by Mario F.; 06-05-2006 at 04:44 PM. Reason: because i'm a twit
    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  5. #5
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    . . . ignoring the fact that case label values must be integral constants. (And that since C++ is case-sensitive, Case won't work. )
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  6. #6
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446
    *blush*

    edited
    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  7. #7
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    You forgot a semicolon.

    Your textbook should explain this. You don't need to read everyone's two cents.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  8. #8
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446
    that's what when I write code on the quick reply box
    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  9. #9
    Registered User
    Join Date
    Apr 2006
    Posts
    38
    Why on Earth would the designers of C++ just go on to ignore the rest of the case conditions? That is about the same as ignoring in an if else statement. What was there reasoning behind this? Am I just missing something?

  10. #10
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446
    Consider a switch statement as a production line. When you put something on the catwalk, it keeps on going until either:

    1. You stop it from moving because of some condition,
    2. You reach the end of the line.

    Without break statements, you would have to produce spaghetti code involving lots of elseif statements.
    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  11. #11
    Registered User
    Join Date
    Apr 2006
    Posts
    38
    Still did not answer my question on why the devlopers did this. What was there rational? It seems stupid. Its like have multiple ifs and if one if is meet it executes the rest of the if statements even though the condition is not meet.

  12. #12
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446
    It did answer your question. The problem is that you are comparing switch statements to if statements. Don't do that. Same type of argument could arise from comparing while with for statements.

    Switch statements offer a program flow that can be matched with if and else. However, it would be cumbersome, considerably harder to code, wouldn't convey the true meaning of what the original programmer intended and would be much more prone to error, given all of the above.

    If this is still confusing you, don't look at case labels as conditions. The condition is present after the switch keyword inside parenthesis. Look at case labels as entry points of a program flow redirection.

    A switch statement is a construct with one of two purposes.

    1. It can either be used is a... switch with many positions that performs a set of tasks for a given position and then exits, not doing any of the other tasks for the other switch positions. (this is the most usual scenario. A switch statement with breaks on most, if not all case labels)

    2. Or it can be used as a workflow type of construct. (A switch statement with few, if any, break statements)

    Imagine a car production line on a car factory.

    - Every stop in which a robot or human either attaches a door to the car or places the windshields, or paints the car, or something else, is a case label.

    - Some work is done on the car on that case label. But the production line didn't stop. The car moves on to the next case label. And it goes on doing this until it reaches the end of the production line and is ready to go to the road.

    - On every case label of this car production line, you can set situations on which the car breaks off the production line. The window that was being attached has a scratch, the robot leaked oil,... You create a break, moving the car off the production line.

    - You can also insert a car that is partially built on any case label on the production line. However, you don't want to insert a car with windows on the case label that attaches windows. You probably want to place it on the next case label.

    A switch statement was not a "stupid" thing someone just decided to include on a programming language to make fun of poor programmers. It is in fact a extremely useful construct.
    Last edited by Mario F.; 06-06-2006 at 05:30 AM.
    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  13. #13
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > Still did not answer my question on why the devlopers did this
    It's a source of ongoing debate - it's just the way it is (like why some operators have the wrong precedence).
    http://www.cs.bell-labs.com/who/dmr/chist.html
    http://www.lysator.liu.se/c/ (when it's up).

    On the plus side, it allows Duff's device to be implemented
    http://www.catb.org/jargon/html/D/Duffs-device.html
    On the minus side, it allows Duff's device to be implemented

    > Its like have multiple ifs
    But only when each case has a break, does it resemble an if/else if statement.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 03-05-2009, 11:32 AM
  2. switch case statement
    By stanlvw in forum C++ Programming
    Replies: 3
    Last Post: 02-26-2008, 05:06 AM
  3. Replies: 27
    Last Post: 10-11-2006, 04:27 AM
  4. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  5. Changing bkgrnd color of Child windows
    By cMADsc in forum Windows Programming
    Replies: 11
    Last Post: 09-10-2002, 11:21 PM