break a while statement

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mar11
    New Member
    • Sep 2009
    • 38

    break a while statement

    hallo all,

    how could I break the while statement inside the switch statement as follows:

    Code:
    enum st {s0, s1} state;
    while(true)
    {
    switch (state)
    
    case s0:
    // do something
    break;
    
    case s1:
    if(condition)
    //do something
    break;   //=======> here the while statement should be broken
    else
    //do something
    break;  //========> here the break of the case s1
    
    }
    any suggestion please..

    best regards..
    Last edited by Banfa; Jul 29 '10, 03:14 PM. Reason: Added [code]...[/code] tags
  • code green
    Recognized Expert Top Contributor
    • Mar 2007
    • 1726

    #2
    Use a variable in the while condition and set this to false inside case.
    Code:
    jump = 1;
    while(jump)
    {
        switch (state)
        {
        case s0:
        // do something
        break;
    
        case s1:
        if(condition)
        //do something
        jump = 0;
        break; //=======> here the while statement should be broken
         else
        //do something
        break; //========> here the break of the case s1
        }
    }
    Hmmm, you will also need an escape form the while to prevent an infinite loop.
    Why are you using a while loop around the switch anyway?
    It seems unnessescary
    Last edited by code green; Jul 29 '10, 12:03 PM. Reason: After thought

    Comment

    • Oralloy
      Recognized Expert Contributor
      • Jun 2010
      • 988

      #3
      Basically code_green has the answer.

      There's always "goto". And now that I've recommended that, just forget I ever did.

      Otherwise, introduce an exit condition, as code_green recommends - either a loop control variable or an "exit" state.

      Code:
      enum st {s0, s1, sExit} state;
      while(state != sExit)
      {
        switch (state)
        {
        case s0:
          // do something
          break;
      
        case s1:
          if(condition)
          {
            //do something
            state = sExit;
          }
          else
            //do something
          break;
        }
      }

      Comment

      Working...