break in switch statement

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • srshamla
    New Member
    • Sep 2007
    • 1

    break in switch statement

    Code:
                      int ch;
                      cin>>ch;
                      switch(ch)
                      {
                       case 1:
                       cout<<"one";
                       break;
                       case 2:
                       cout<<"two";
                       break;
                       case 3:
                       cout<<"three";
                       break;
                      }
    When we trace the above code, I choose value 3 for the variable ch, then the compiler switches to case 3 and print statement "three". After printing this the compiler goes to case 1's break instead of going case 3's break.why?
  • pbmods
    Recognized Expert Expert
    • Apr 2007
    • 5821

    #2
    Heya, srshamla. Welcome to TSDN!

    I'm going to go ahead and move this thread to the C forum, where our resident Experts will be better able to help you out.

    Comment

    • Ganon11
      Recognized Expert Specialist
      • Oct 2006
      • 3651

      #3
      What do you mean, 'it goes to case 1's break'?

      Comment

      • sicarie
        Recognized Expert Specialist
        • Nov 2006
        • 4677

        #4
        Originally posted by Ganon11
        What do you mean, 'it goes to case 1's break'?
        The debugger in step-through mode. I'm guessing that it's some compiler-specific "optimizati on" or the closing of the switch statement (when you step through, a lot of the time it bounces back up to the check to close the loop). However, the case 3 break is definitely not ignored - you can manipulate its place (put things before and after), and see that it is definitely being caught there.

        Comment

        • JosAH
          Recognized Expert MVP
          • Mar 2007
          • 11453

          #5
          Originally posted by sicarie
          The debugger in step-through mode. I'm guessing that it's some compiler-specific "optimizati on" or the closing of the switch statement (when you step through, a lot of the time it bounces back up to the check to close the loop). However, the case 3 break is definitely not ignored - you can manipulate its place (put things before and after), and see that it is definitely being caught there.
          It's the code generator to blame and the short term memory of it: once the jump
          out of the switch statement has been found (possibly it was a 'short' and 'relative'
          jump, jump to that jump instruction and all will be fine. Possibly a later code
          generating/optimizing pass over the code can remove cascaded jumps as well.

          kind regards,

          Jos

          Comment

          Working...