0

I would like to know is there a way to to return back to the last iteration of the for loop, after the break and continue from there, for ex.:

void loop()
{
    for (n ; n<10; n++)
        if (n=5) { break; }
}

// code

loop();  // should start from 6 ...
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
Alshatri
  • 19
  • 1
  • 1

3 Answers3

1

Write a class:

class my_loop
{
    int i;
public:
    my_loop(): i(0) {}
    void loop_some()
    {
        while (i != some_limit)
            ...
    }
};

The instance of the class contains the necessary info for running the loop. You can return from loop_some() and call it again when necessary.

Ulrich Eckhardt
  • 16,572
  • 3
  • 28
  • 55
0

Declare n as a static variable, (static int n=0) so it retains its value and use continue instead of break.

void loop()
 {
      static int n=0;
      for (; n<10; n++){

          if (n==5  ){  

             cout<<"  n = 5   "; 
             continue; 
          }

            cout<<""<<n<<" ";
       }

}

Output:

0 1 2 3 4   n = 5   6 7 8 9
 Press any key to continue
Software_Designer
  • 8,490
  • 3
  • 24
  • 28
-1

What i could think of would be to use goto to to leave and go back into your loop. But you should try to avoid this because it leads to very difficult readable code. Here are two links which could help to decide:

Use goto or not

Statements and flow control

Community
  • 1
  • 1
ExOfDe
  • 190
  • 1
  • 12