Thread: switch question

  1. #16
    Registered User
    Join Date
    Jan 2005
    >> Is that smart to do? Would you pros do that?
    In some situations, yes. You have to be very careful, though, because it is an easy thing to miss. You should make it obvious that you purposefully didn't put in the break, and you should make it obvious that the code under the next case counts for multiple cases. For example, notice how the comments help indicate what you are doing so that when you or somebody else comes back to maintain or update the code, there is less chance of confusion.
    switch (val)
        case 1:
        case 2:
        case 3:
        case 4:
            // fall through on purpose!
        // case 4:
        case 5:
    If you can do something in a manner that is more clear than the above, you should choose that version instead. Even with the comments I don't like the above code.
    Last edited by Daved; 11-08-2006 at 11:21 AM.

  2. #17
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    Lookup "Duff's device" if you want to see switch/case "abuse"
    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.

  3. #18
    Reverse Engineer maxorator's Avatar
    Join Date
    Aug 2005
    Forgetting to place a break after each case will only cause it to "fall through" to the next one anyway. I always make sure I end my cases with a break, it makes good sense, unless of course the idea of the program is to test the weakness in a switch statement that is
    Sometimes I forget to end the case before WM_DESTROY with a break, so my program just exits when the that case is activated. First time when this happened I was quite confused.
    "The Internet treats censorship as damage and routes around it." - John Gilmore

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. another do while question
    By kbpsu in forum C++ Programming
    Replies: 3
    Last Post: 03-23-2009, 12:14 PM
  2. Switch Case Question
    By dnysveen in forum C++ Programming
    Replies: 12
    Last Post: 06-06-2006, 05:34 AM
  3. Replies: 7
    Last Post: 05-25-2006, 12:51 PM
  4. Exam Question - Possible Mistake?
    By Richie T in forum C++ Programming
    Replies: 15
    Last Post: 05-08-2006, 03:44 PM
  5. Very simple question, problem in my Code.
    By Vber in forum C Programming
    Replies: 7
    Last Post: 11-16-2002, 03:57 PM