-2

I have Nested do-while, while, and for loops.

Is there a way to decide which loop to "continue" to? A variety of solutions would be great (not only goto..) Thank you!

while (foo==true) // loop1
{

   do
   {
      for(int i=0; i<someNumber ; i++) // loop3
      {

         if( soo==1)
         {
             <CONTINUE_TO_LOOP1>
         }
         else if( soo==2 )
         {
             <CONTINUE_TO_LOOP2>
         }
         else if( soo==3 )
         {
             <CONTINUE_TO_LOOP3>
         }

      }

   } while (moo==true) //loop2    

}
Farah
  • 2,469
  • 5
  • 31
  • 52

4 Answers4

1

CONTINUE_TO_LOOP3 simple:continue

CONTINUE_TO_LOOP2 easy: break

CONTINUE_TO_LOOP1 this is the interesting one:

  • cant do that in a single step without using the four letter word goto
  • or placing a try-catch around loop2 and using a raise to get out.
  • or assuming there are no code between the end of loop1 and the end of loop2: moo = false ; break ;
Jasen
  • 11,837
  • 2
  • 30
  • 48
1

Probably you can do this work around.

while (foo==true) // loop1
{

   do
   {
      for(int i=0; i<someNumber ; i++) // loop3
      {

         if( soo==1)
         {
              break;//<CONTINUE_TO_LOOP1>
         }
         else if( soo==2 )
         {
             break;//<CONTINUE_TO_LOOP2>
         }
         else if( soo==3 )
         {
            continue;//<CONTINUE_TO_LOOP3>
         }
      }
      if( soo==1)
      {
         break;//<CONTINUE_TO_LOOP1>
      }
      else if( soo==2 )
      {
          continue;//<CONTINUE_TO_LOOP2>
      }
   } while (moo==true) //loop2    
   if( soo==1)
   {
       continue;//<CONTINUE_TO_LOOP1>
   } 
}
Sridhar DD
  • 1,972
  • 1
  • 10
  • 17
  • 1
    May i know the reason it is down voted? This solution will surely work and i already mentioned its work around. – Sridhar DD Dec 26 '14 at 10:29
1

With some restructuration, and without goto:

bool loop3()
{
    for (int i=0; i < someNumber ; i++) {
        if(soo == 1) {
            return false;
        } else if(soo == 2) {
            return true;
        } else if(soo == 3) {
            continue;
        }
    }
    return true;
}

And the loops become:

while (foo == true) // loop1
{
   do
   {
       if (loop3() == false) {
           break;
       }
   } while (moo == true) //loop2    
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302
1

I advocate unconditional branches to expressive labels. Other solutions will cost extra conditional branches and possibly state variables, will be less flexible, and can be much less readable.

  • I also advocate ""Go To Statement Considered Harmful" Considered Harmful". –  Dec 26 '14 at 11:49