Break Out To Top Of Loop

Mar 26, 2011 at 1:09pm
Hi All.

I have a piece of code in a while loop where if something happens, I want to go back to the start of the loop. Is there any way to do that?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
while(placementFailure)
    {
        if(d=='h')
        {
            cS=checkSpaces(grid, col, row, BoatSize, d);
            if(cS==1)
            {
                d=getDirection(rand()%10);
                col=resetColAndRow(col, row, BoatSize, d);
                GO BACK TO TOP OF LOOP HERE...
            }
            cout << "do edit grid from IF HORIZONTAL" << endl;
            editGrid(grid, col, row, BoatSize, d);
            return 0;
        }//end of 'if horizontal'
        else
        {
            cS=checkSpaces(grid, col, row, BoatSize, d);
            cout << "checkSpaces is: " << checkSpaces << endl;
            if(cS==1)
            {
                d=getDirection(rand()%10);
                col=resetColAndRow(col, row, BoatSize, d);
                cout << "if not checkSpaces..." ;
                GO BACK TO TOP OF LOOP HERE...
            }
            cout << "do edit grid FROM VERTICAL" << endl;
            editGrid(grid, col, row, BoatSize, d);
            return 0;
        }
     }
}//end of setBoat function 


Thanks!
Mar 26, 2011 at 1:12pm
You could try nested while loops, and add the break; keyword when you want to end the while loop you're in.

1
2
3
4
5
6
7
8
9
10
11
12
bool exit = false;

while( ! exit )
{
    while( placementFailure )
    {
        ...code
        break;
    }

//this will restart the second while loop
}
Mar 26, 2011 at 1:18pm
continue; could help you too.
1
2
3
4
5
6
7
int i = 0;
while (i != 10)
{
    i++;
    continue;
    cout << "cat\n";
}

continue jumps back to the beginning of the loop. so in this little example cat will never be printed.
Mar 26, 2011 at 1:19pm
Just use continue keyword.
Last edited on Mar 26, 2011 at 1:20pm
Mar 26, 2011 at 1:23pm
Oh, or that! I've never used continue; :O
Mar 26, 2011 at 1:34pm
continue
works great, thanks!
Topic archived. No new replies allowed.