Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 135 ยท Control Flow

break, continue and goto

Learn how break and continue control C loops, how to leave nested loops, and why goto for error cleanup is the one use of goto that C programmers accept.

Loops normally run until their condition turns false. Real programs need more control than that: you find what you were searching for halfway through the data, you meet a line of input you want to skip, or something fails and you must clean up and get out. C has three jump statements for these moments. break leaves a loop (or a switch) immediately, continue skips to the next iteration, and goto jumps to a label anywhere in the same function.

break and continue are everyday tools. goto has a bad reputation, mostly deserved, but C programmers still use it for one job that C has no better tool for: releasing resources on every error path of a function. This lesson shows all three, the traps around switch and while loops, and how to leave nested loops cleanly.

break: leave the loop now

break ends the innermost enclosing for, while, do-while or switch at once. Execution continues with the first statement after it. The rest of the body is skipped, and the condition is not checked again.

The classic use is a search: as soon as you've found the item, there is nothing left to do.

C Stop at the first match

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The loop checks indexes 0, 1 and 2, finds -3 at index 3 and stops. The values 25, -8 and 14 are never examined. The -1 "not found" marker is a common C convention, because valid indexes are never negative.

The loop-and-a-half

Sometimes the natural exit point sits in the middle of the body: you must read something before you know whether to stop. An infinite loop, while (1) or for (;;), with a break at exactly that spot expresses it directly:

C Read commands until quit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The program processes three commands, stops at quit and never reads add 1000, so the final total is 13. Remove the quit line from the Input box and the loop ends through the first break instead, when fgets returns NULL at the end of input. (strncmp compares the first 4 characters; see String Functions.)

An infinite loop with break is fine as long as every exit is easy to spot. If a loop has five breaks spread over 50 lines, readers can't tell when it ends; move parts of the body into functions or rethink the condition.

continue: skip to the next iteration

continue abandons the current iteration of the innermost loop and jumps to the point where the loop decides whether to go again:

  • In a while or do-while, that's the condition.
  • In a for, it's the update expression (such as i++), then the condition.

Use it to filter out items you don't want, so the main work isn't buried inside a big if:

C Skip comments and bad data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The program warns about line 4 and prints a total of 445 cents. Each continue is a guard clause: it deals with a special case and gets out of the way, so the code that does the real work stays at the left margin.

Notice that line_number++ comes before every continue. If it came after one, skipped lines wouldn't be counted and the line numbers in the messages would be wrong. That leads to a nastier trap.

The skipped-update trap

In a for loop, continue still runs the update, because the update belongs to the loop header. In a while loop, the "update" is just an ordinary statement in the body, and continue jumps right over it:

C
int i = 0;
while (i < 10) {
    if (i % 3 == 0) {
        continue;    /* BUG: i++ below never runs, so i stays 0 forever */
    }
    printf("%d\n", i);
    i++;
}

This loop never ends. Update before the continue, or better, write it as a for loop, where continue can't skip the update:

C
for (int i = 0; i < 10; i++) {
    if (i % 3 == 0) {
        continue;    /* i++ still runs */
    }
    printf("%d\n", i);    /* 1 2 4 5 7 8 */
}

break and continue inside a switch

A switch uses break to end each case, and that's where the "innermost" rule catches people. When a switch is inside a loop, a break inside the switch leaves only the switch. continue ignores the switch completely and applies to the loop.

C A menu loop with a switch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output ends with bye, final volume 6: the last + is never processed because q cleared the running flag. The unknown command ? prints its message, and its continue skips the "volume" line. If you change the q case to a bare break;, the loop keeps going, prints volume: 6 again for q and ends with volume 7.

To leave a loop from inside a switch, set a flag like running above, or put the loop in a function and return from it. Both read better than the alternatives.

Leaving nested loops

break exits one level only. Inside nested loops, the inner break lands you in the outer loop, which carries on. C has no labeled break (Java and JavaScript have break outer;), so you need a plan:

  1. A flag that the outer loop checks.
  2. A function that contains the loops and returns when it's done. This is usually the cleanest.
  3. goto to a label right after the loops.

Here are all three, searching a seating plan for the first free seat (0):

C Three ways out of nested loops

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

All three report row 1, seat 2, and none of them looks at row 2. The function version gives the search a name and can be reused; its results come back through the pointer parameters row_out and col_out, a technique explained in Parameters and Return Values. The flag version is easy to break by forgetting the && !found. The goto version is short and clear here, because the label sits right after the loops. Many C style guides accept goto for exactly this, though a function is still the first choice.

goto: jumping to a label

goto label; moves control to the statement marked label: in the same function. A label is an identifier followed by a colon, and it can appear before any statement. Labels have function scope: you can jump forward or backward, but never into another function.

C is more permissive than C++ here. C++ refuses to jump over an initialization, but in C a goto may skip past int x = 5; into the scope of x. The variable then exists but was never initialized, so reading it is a bug. The one hard rule in C is that you can't jump into the scope of a variable-length array (Multidimensional Arrays covers VLAs).

Why do style guides warn against goto?

  • It hides the structure. A loop, an if or a return shows its shape at a glance. A goto can go anywhere, so you have to find the label and think about every path that reaches it. Code full of jumps is called "spaghetti code".
  • Structured statements cover almost everything. Loops replace backward jumps, if/else replaces forward jumps, and functions with return replace early exits.

There is one job, though, where goto is the accepted C idiom.

goto for cleanup: the one accepted use

C has no destructors and no exceptions. When a function acquires several resources (memory, files, locks) and any step can fail, every failure path must release exactly what was acquired so far. Without goto, the cleanup code gets copied into every error branch, and sooner or later one copy is wrong. With goto, each failure jumps to a cleanup ladder at the end of the function, where resources are released in reverse order:

C Cleanup with goto

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Read the three runs carefully. With fail_step = 0, everything succeeds and the function falls through the whole ladder: close the file, free the text, free the numbers. With fail_step = 1, it jumps to free_numbers and releases only the one buffer it got. With fail_step = 2, it frees both buffers and skips fclose, because no file was opened. Every exit path releases exactly the right things, and there is a single return at the bottom.

This pattern is used throughout the Linux kernel, SQLite, CPython and many other large C code bases. The rules that keep it readable:

  • Jump forward only, to labels near the end of the function.
  • Name labels after what they do (free_text, close_file), and order them in reverse order of acquisition.
  • Use goto only for this cleanup, never as a general-purpose loop.

Error Handling builds on this with errno and error codes.

Before C23, a label had to be followed by a statement, so you couldn't put a label right before a declaration or right before a closing brace. Older code works around this with an empty statement: out: ;. C23 lifts the restriction, and GCC accepts it in C23 mode.

Common mistakes

  • Expecting break to leave several loops. It leaves one. Use a function, a flag or a cleanup-style goto.
  • Using break inside a switch to stop the enclosing loop. It stops only the switch.
  • A continue that skips the update in a while loop, producing an infinite loop.
  • break inside an if that isn't in a loop or switch. An if is not something you can break out of; the compiler reports break statement not within loop or switch.
  • Backward gotos that build loops. Write a real loop instead.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? for (int i = 0; i < 6; i++) { if (i == 4) break; printf("%d ", i); }

    When i reaches 4, break ends the loop before the printf runs, so only 0 to 3 are printed.
  2. 2. What does this print? for (int i = 1; i <= 5; i++) { if (i % 2 == 0) continue; printf("%d ", i); }

    continue skips the printf for even numbers, but in a for loop the update i++ still runs, so the odd numbers 1, 3 and 5 are printed.
  3. 3. A switch sits inside a while loop. What does break in one of its cases do?

    break exits the innermost enclosing switch or loop, which here is the switch. Use a flag or a return to stop the loop.
  4. 4. In the goto-cleanup pattern, in what order should resources be released?

    The labels form a ladder. A failure at step N jumps to the label that releases resources N-1, N-2, ... 1, falling through the later labels, so the order must be the reverse of acquisition.
  5. 5. What happens with int i = 0; while (i < 5) { if (i == 2) continue; i++; }?

    Once i is 2, continue jumps back to the condition without running i++, so i stays 2 forever. In a for loop the update would still run.

Summary

  • break ends the innermost loop or switch immediately.
  • continue skips the rest of the current iteration. A for loop still runs its update; a while loop can skip your manual update and loop forever.
  • Inside a switch in a loop, break leaves only the switch, while continue applies to the loop.
  • C has no labeled break. To leave nested loops, use a function with return (usually best), a flag, or a goto to a label just after the loops.
  • goto jumps to a label in the same function. Its accepted use in C is a forward jump to a cleanup ladder that releases resources in reverse order.

Next: Functions, where you'll split programs into named, reusable pieces.