Lesson 6 of 6 · Control Flow · 3 min read · Updated
break, continue and goto
Leaving a loop early, skipping one turn, and the one place goto is still acceptable.
continue — skip the rest of this turn
#include <stdio.h>
int main(void)
{
for (int i = 1; i <= 10; i++) {
if (i % 3 == 0) {
continue; /* skip multiples of 3 */
}
printf("%d ", i);
}
printf("\n");
return 0;
}
1 2 4 5 7 8 10
continue jumps straight to the next turn. In a for loop the step (i++) still runs; in a while loop make sure the variable was already changed, or the loop never ends.
break — leave the loop now
#include <stdio.h>
int main(void)
{
int nums[] = {4, 9, 15, 7, 22};
for (int i = 0; i < 5; i++) {
if (nums[i] > 10) {
printf("First over 10: %d at position %d\n", nums[i], i);
break; /* no need to look further */
}
}
return 0;
}
First over 10: 15 at position 2
goto — only to escape nested loops
#include <stdio.h>
int main(void)
{
int grid[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 3; c++) {
if (grid[r][c] == 5) {
printf("Found 5 at row %d, column %d\n", r, c);
goto done; /* leaves BOTH loops */
}
}
}
printf("Not found\n");
done:
printf("Search finished\n");
return 0;
}
Found 5 at row 1, column 1
Search finished
goto label; jumps to the line marked label:. A break leaves only the innermost loop, so escaping two loops at once is the classic case where goto is clearer than the alternatives.
Warning
Do not use goto as a loop or to jump backwards. Code that jumps around freely ("spaghetti code") is very hard to follow and fix. Use it only to jump forward out of nested loops or to a single clean-up section at the end of a function.
Inside two nested loops, what does break leave?
Try this now
- Print the numbers 1 to 50 but skip every number that ends in 5 or 0, using continue.
- Read numbers until the user enters a negative one, then print their total (use break).
- Rewrite the goto search using a
foundflag instead, and decide which version is clearer.
Create a free account to save your progress, or sign in.