Reputation: 75
I have 2 loops like the code below:
for(NSString *link in pageLinks){
for(NSString *pattern in disallowedPattern){
if (range.location != NSNotFound )
// if condition is yes go back to the first loop.
}
}
I want the program to return to the first loop if the condition is yes. I used continue
, but it just returns to the second loop. What is the solution to this?
Upvotes: 1
Views: 3586
Reputation: 753615
A break;
in the inner loop resumes the outer loop immediately after the inner loop.
for (NSString *link in pageLinks)
{
for (NSString *pattern in disallowedPattern)
{
if (range.location != NSNotFound)
break;
}
...execution continues here after break is executed...
}
There's a question lurking in the comment:
That is exactly the other problem that I've got; [I want to skip the] 'something' after the second for loop as well; is there any solution to this again?
I hope I've interpreted it correctly. There are two possibilities, at least. Which you choose depends in part on your attitude to goto
statements.
goto
) for (NSString *link in pageLinks)
{
for (NSString *pattern in disallowedPattern)
{
if (range.location != NSNotFound)
goto end_of_outer_loop;
}
...other code to be executed if the loop terminates...
end_of_outer_loop: ; // Null statement after the colon
}
goto
) for (NSString *link in pageLinks)
{
bool found = false;
for (NSString *pattern in disallowedPattern)
{
if (range.location != NSNotFound)
{
found = true;
break;
}
}
if (!found)
{
...other code to be executed if the loop terminates...
}
}
Both work; both are reasonably clear. It is mostly a matter of taste which you choose.
Upvotes: 2
Reputation: 5456
You should use break
. The continue
keyword just restart the current loop. (In for
loops, continue
will do the increment before restarting.)
Upvotes: 3
Reputation: 25318
break
is what you want. It will terminate the current loop and, in your case, get back to the first one.
Upvotes: 7