Thuta Learning
C
BasicProgrammingBeginner

Break/Continue

CLesson 1520 min

What you'll walk away with

  • Trace where execution continues after break and after continue
  • Explain how continue differs between for and while, and avoid the resulting infinite loop
  • Know that a break inside a switch leaves only the switch
  • Leave two nested loops at once with a flag or a return

Explain it simply

Explain it simply

Imagine checking the books on a shop shelf one by one, looking for a particular title. When you reach a book with a torn cover, you skip that one and move on to the next: that is continue. When you find the book you want, you stop looking at the rest of the shelf: that is break.

Both keywords cut the normal flow of a loop short, but by different amounts: continue cuts only the current pass, break cuts the whole loop.

Problem → Why → Solution

The problem: one continue freezes a while loop

You want to print the numbers from 0 to 9 but skip the multiples of 3. The logic works in a for loop, but rewritten as a while loop the program prints nothing and hangs immediately. i starts at 0, and 0 % 3 == 0, so continue runs on the very first pass.

skip_bug.c
#include <stdio.h>

int main(void) {
    int i = 0;
    while (i < 10) {
        if (i % 3 == 0) {
            continue;       /* jumps back to the test: i is still 0 */
        }
        printf("%d\n", i);
        i++;                /* never reached when i % 3 == 0 */
    }
    return 0;
}

Why does this happen?

In a while loop, continue jumps straight to the condition and skips everything left in the body, including i++. So i stays 0, i < 10 is tested again, continue runs again, and so on forever. In a for loop, continue jumps to the update (i++) first, so the problem does not exist there. The compiler gives no warning, because the code is perfectly valid C.

Core concept: two jumps and where they land

break and continue are jumps that cut a loop pass short. break ends the innermost enclosing loop at once: the rest of the body is skipped, the condition is not tested again, and execution resumes at the first statement after the loop. continue ends only the current pass: the rest of the body is skipped and the loop moves on to its next pass.

Where continue lands depends on the loop. In a for loop it jumps to the update (i++) first and then to the condition, so the counter still advances. In a while or do...while loop it jumps straight to the condition. If the update is written at the bottom of the body, continue skips it and the loop tests the same value forever. That single difference is why a continue that is harmless in a for loop can freeze a while loop.

Both keywords affect only the innermost enclosing construct. break also ends a switch, so a break inside a switch that sits inside a loop leaves the switch, not the loop. continue has no meaning for a switch and applies to the surrounding loop. In nested loops, a break in the inner loop stops only the inner loop, and the outer loop carries on with its next pass. Standard C (up to C23) has no labelled break like Java's, so leaving two loops at once needs a flag, a return from a function, or a goto to a label after the loops.

Used well, these jumps make loops clearer: break says "found it, stop searching", and a continue at the top of the body acts as a guard clause that filters out unwanted items, so the main work is not buried inside a deep if. Used carelessly, they hide the exits in the middle of a long body.

text
Where continue and break jump in a for loop
-------------------------------------------
          +----------------------------------+
          | continue: i++ then test i < 10   |
          v                                  |
  for (int i = 0; i < 10; i++) {             |
      if (i == 4) continue;  ----------------+
      if (i == 8) break;     -------------+
      printf("%d ", i);                   |
  }                                       |
  printf("\n");  <------------------------+  break: first line after loop
Mental model: cut the pass, or cut the loop
  1. continue: skip the rest of this pass
  2. In for, the update still runs
  3. In while, jump straight to the test
  4. break: leave the innermost loop/switch

Neither keyword can reach past the innermost loop (or, for break, the innermost switch).

General pattern

c
for (init; condition; update) {
    if (item_is_unwanted) {
        continue;       /* go on with the next pass */
    }
    if (work_is_finished) {
        break;          /* leave the loop now */
    }
    do_the_work;
}

Put continue near the top of the body as a guard clause, and pair break with a clear "we are done" condition. Both are statements, so each needs a semicolon after it.

Example: skip one number, then stop

The first loop shows the two keywords side by side: it skips 4 and stops at 8. The second shows break's most common job, finding the first value that matches.

break_continue.c
#include <stdio.h>

int main(void) {
    for (int i = 0; i < 10; i++) {
        if (i == 4) {
            continue;           /* skip the rest of this pass only */
        }
        if (i == 8) {
            break;              /* leave the loop completely */
        }
        printf("%d ", i);
    }
    printf("\n");

    int found = -1;             /* -1 means "not found yet" */
    for (int n = 50; n <= 100; n++) {
        if (n % 7 == 0) {
            found = n;
            break;              /* the first match is enough */
        }
    }
    printf("First multiple of 7 from 50: %d\n", found);
    return 0;
}

Code breakdown

  1. continue at 4continue; /* skip the rest of this pass only */

    When i is 4 the printf is skipped, but because this is a for loop i++ still runs and the next pass starts with i == 5. That is why only 4 is missing from the output.

  2. break at 8break; /* leave the loop completely */

    When i reaches 8 the whole loop ends. Neither 8 nor 9 is printed, i < 10 is never tested again, and execution goes straight to printf("\n").

  3. A "not found" markerint found = -1; /* -1 means "not found yet" */

    If no number in the range matches, break never runs, the loop ends normally and found keeps -1. That lets the code after the loop tell whether anything was found.

  4. Stop at the first matchif (n % 7 == 0) {

    56 is the first multiple of 7 after 50. Without the break, the loop would keep going to 100 and overwrite found with 63, 70 and so on, ending with the last match, 98, instead of the first.

You should see
0 1 2 3 5 6 7
First multiple of 7 from 50: 56

break inside a switch inside a loop

From the Switch lesson you know each case ends with break. Put that switch inside a loop and the break leaves only the switch, while the loop keeps going. The code below prints (i=...) on all three passes even though case 1 ends with break. This is the source of the menu-loop bug where a "quit" option written as break does not quit: set a flag that the loop condition checks, or use return.

switch_in_loop.c
#include <stdio.h>

int main(void) {
    for (int i = 0; i < 3; i++) {
        switch (i) {
        case 1:
            printf("one ");
            break;              /* leaves the switch, NOT the loop */
        default:
            printf("other ");
            break;
        }
        printf("(i=%d) ", i);
    }
    printf("\n");
    return 0;
}

Leaving two nested loops at once

The code below searches a 5 x 5 grid for the first cell where row * col == 12. The break in the inner loop leaves only the inner loop, so it also sets a done flag, and the outer loop's condition (row <= 5 && !done) checks that flag. Moving the search into a function is often cleaner still, because return leaves both loops in one step (functions come a few lessons later).

grid_search.c
#include <stdio.h>

int main(void) {
    int target = 12;
    int found_row = 0, found_col = 0;
    int done = 0;               /* flag that tells the outer loop to stop */

    for (int row = 1; row <= 5 && !done; row++) {
        for (int col = 1; col <= 5; col++) {
            if (row * col == target) {
                found_row = row;
                found_col = col;
                done = 1;
                break;          /* leaves the inner loop only */
            }
        }
    }
    printf("%d = %d x %d\n", target, found_row, found_col);
    return 0;
}

In real projects

Where this shows up in real projects

In real C code, break and continue mostly appear in three shapes. Search loops break at the first match: looking up a user ID in a table, finding the first free slot in a fixed-size array. Filter loops use continue as a guard: a log parser skips blank lines and lines starting with #, and a CSV importer skips rows that fail validation while counting them. Event loops run forever with for (;;) and break when a "quit" message arrives.

Reviewers look extra carefully when a loop pass owns a resource. If each pass opens a file or allocates memory, a continue or break in the middle can skip the matching fclose() or free(), leaking one resource per pass. The defence is to clean up before jumping, or to structure the body so every exit passes through a single cleanup point, and then to exercise each jump path with its own test case.

Common mistakes

Common mistakes

1. Skipping a while loop's update with continue

This is the bug from the problem section: continue skips the i++ at the bottom of the body and the loop is stuck on one value. Update before continuing (if (i % 3 == 0) { i++; continue; }), or rewrite the loop as a for loop, where the update always runs.

2. Expecting a break in a switch to leave the loop

In a menu loop, case 'q': break; leaves only the switch and the menu is shown again. Set a flag such as running = 0; that the loop condition checks, or use return.

3. Expecting an inner break to stop every loop

You break when the grid search finds a match, but the outer loop moves on to the next row, keeps searching, and overwrites the result if it finds another match. Use the flag pattern from the deeper section, or a return from a function.

4. Jumping over cleanup

After FILE *f = fopen(name, "r");, a line like if (line_is_bad) continue; skips fclose(f) every time a bad line appears. Close the resource before you jump.

Best practices

Best practices

  • Use continue as a guard clause near the top of the body, not scattered through the middle.
  • Give search loops that end with break a "not found" marker such as -1 or a flag.
  • Every time you write continue in a while loop, check that it does not skip the update.
  • When you need to leave two loops, consider moving the search into a function and using return.

Mini challenge

Mini challenge: add until the budget runs out

Add the numbers from 1 to 20 to a running total, but skip multiples of 3 with continue. As soon as the total goes over 40, stop with break, then print the numbers you added, the total and the number where you stopped.

  • Use one continue and one break inside a single for loop
  • 3, 6, 9 and the other multiples of 3 are neither added nor printed
  • Print every number you add on the "added:" line
  • Stop after adding the number that pushes the total over 40, then print "total: ... (stopped at ...)"
budget.c
#include <stdio.h>

int main(void) {
    int total = 0;
    int last = 0;

    printf("added:");
    for (int n = 1; n <= 20; n++) {
        // TODO: skip multiples of 3 with continue

        // TODO: add n to total, remember it in last, print " n"

        // TODO: break once total is over 40
    }
    // TODO: print "total: <total> (stopped at <last>)"
    return 0;
}

Expected: The program prints these two lines: added: 1 2 4 5 7 8 10 11 total: 48 (stopped at 11)

Show hint

The order of the two checks matters: the continue check comes before the addition, and the break check comes after it, so the number that crosses 40 is still included in the total.

Show solution
budget.c
#include <stdio.h>

int main(void) {
    int total = 0;
    int last = 0;

    printf("added:");
    for (int n = 1; n <= 20; n++) {
        if (n % 3 == 0) {
            continue;           /* multiples of 3 are skipped */
        }
        total += n;
        last = n;
        printf(" %d", n);
        if (total > 40) {
            break;              /* budget exceeded: stop */
        }
    }
    printf("\ntotal: %d (stopped at %d)\n", total, last);
    return 0;
}

Quick quiz 1 / 3

What does for (int i = 1; i <= 6; i++) { if (i % 2) continue; printf("%d ", i); } print?

Quick quiz 2 / 3

What does for (int i = 0; i < 3; i++) { switch (i) { case 1: break; } printf("%d ", i); } print?

Quick quiz 3 / 3

What does for (int r = 0; r < 3; r++) for (int c = 0; c < 3; c++) { if (c == 1) break; printf("%d%d ", r, c); } print?

What to remember

  • break leaves the innermost loop (or switch) at once; continue skips only the current pass.
  • In a for loop continue still runs the update; in a while loop it jumps straight to the condition and can skip the update.
  • A break inside a switch leaves only the switch, and a break in a nested loop leaves only the inner loop.
  • Give search loops a "not found" marker, and clean up resources before you jump.

GNU C compiler diagnostics — GNU Project

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Break/Continue | Thuta Learning