You can use continue
to terminate the current iteration of a loop without terminating the loop itself. But depending on how your code is structured, an if
statement might be cleaner.
Given your example, you might want:
for (int i = 0; i < 5; i++)
{
int i_foo;
i_foo = foo();
if (i_foo >= 5) {
footwo();
}
}
I'm assuming that you meant to assign the result of foo()
to i_foo
, not to i
.
A continue
can be simpler if you need to bail out from the middle of some nested structure, or if you need to bail out very early in the body of the loop and there's a lot of code that would be shoved into the if
.
But in the case of nested control structures, you need to remember that continue
applies only to the innermost enclosing loop; there's no construct (other than goto
) for bailing out of multiple nested loops. And break
applies to the innermost enclosing loop or switch
statement.