The Analogy: Emergency Exits and Skipped Turns
A loop is a queue of people each taking a turn. Most of the time everyone completes their turn and the queue advances normally.
break is the fire exit. Someone pulls it and the whole queue is abandoned immediately — no more turns, everyone out. continue is much gentler: this person's turn ends early, but the queue carries on with the next person. And goto is a trapdoor to a labelled spot elsewhere in the room, which is why it has a bad reputation and one genuinely excellent use.
The distinction that matters in C is scope. break and continue each affect exactly one loop — the innermost one containing them. Nothing in the language lets break leave two loops at once, and that single limitation is why goto still appears in serious C code.
Syntax or Core Structure
#include <stdio.h>
int main(void) {
/* break: abandon the loop entirely */
for (int i = 1; i <= 10; i++) {
if (i * i > 30) {
printf("stopping at i = %d\n", i);
break;
}
printf("%d squared is %d\n", i, i * i);
}
/* continue: end this pass early, carry on with the next */
for (int i = 1; i <= 10; i++) {
if (i % 3 != 0) {
continue;
}
printf("%d is a multiple of three\n", i);
}
return 0;
}
Output:
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
stopping at i = 6
3 is a multiple of three
6 is a multiple of three
9 is a multiple of three
| Statement | What it abandons | Legal inside |
|---|---|---|
break | the innermost loop or switch | loops and switch |
continue | the rest of the current iteration | loops only |
goto label | jumps to a label in the same function | anywhere |
return | the entire function | anywhere |
Technical Depth: Three Traps and One Legitimate goto
continue in a while skips your increment
In a for loop, continue jumps to the step clause, so the counter still advances. In a while loop there is no step clause — the increment is just a statement at the bottom of the body, and continue skips straight past it.
int i = 0;
while (i < 5) {
if (i == 2) {
continue; /* i is never incremented: infinite loop */
}
printf("%d\n", i);
i++;
}
The same logic written as a for loop is safe, which is a concrete reason to prefer for whenever a counter exists.
break inside a switch inside a loop
break belongs to the nearest enclosing switch or loop, and a switch counts. So this never leaves the loop:
while (running) {
switch (command) {
case 'q':
break; /* leaves the switch only - the while spins on */
}
}
Set a flag, return, or goto a label after the loop. There is no syntax that breaks through a switch to the loop outside it.
break only leaves one loop
/* Searching a grid: this break abandons the inner loop, then the outer
loop simply moves to the next row and keeps searching. */
for (int r = 0; r < ROWS; r++) {
for (int c = 0; c < COLS; c++) {
if (grid[r][c] == target) {
break;
}
}
}
Three real fixes exist, in increasing order of how much most C programmers like them:
/* 1. A flag - correct, but the condition now has two jobs. */
int found = 0;
for (int r = 0; r < ROWS && !found; r++) {
for (int c = 0; c < COLS; c++) {
if (grid[r][c] == target) { found = 1; break; }
}
}
/* 2. A forward goto - honest about what it does. */
for (int r = 0; r < ROWS; r++) {
for (int c = 0; c < COLS; c++) {
if (grid[r][c] == target) { goto found_it; }
}
}
found_it:
;
/* 3. Extract a function and return - usually the best answer. */
static int find_in_grid(int grid[][COLS], int rows, int target) {
for (int r = 0; r < rows; r++) {
for (int c = 0; c < COLS; c++) {
if (grid[r][c] == target) {
return r * COLS + c;
}
}
}
return -1;
}
Option 3 removes the problem rather than working around it: return leaves every loop at once, and the function now has a name that says what the loops are for.
What goto can and cannot do
- It can only jump within the same function. There is no cross-function goto, and no exceptions in C.
- It can jump forwards or backwards, but a backward goto is just a loop written badly. Do not.
- It must not jump into the scope of a variable-length array, and jumping forward over an initialisation leaves that variable indeterminate.
- A label must be followed by a statement.
cleanup: }at the very end of a function is a syntax error before C23 — writecleanup: ;or put areturnthere.
Real World Example: The Cleanup Ladder
C has no destructors, no finally, and no defer. When a function acquires several resources and any acquisition can fail, you need one exit path that releases exactly what was actually obtained. The forward goto is the standard idiom for it, used throughout the Linux kernel, SQLite and libcurl.
#include <stdio.h>
#include <stdlib.h>
int process(const char *in_path, const char *out_path, size_t n) {
FILE *in = NULL, *out = NULL; /* every handle starts empty */
int *buffer = NULL;
int status = 1; /* assume failure until proven otherwise */
in = fopen(in_path, "r");
if (in == NULL) {
perror("open input");
goto cleanup;
}
out = fopen(out_path, "w");
if (out == NULL) {
perror("open output");
goto cleanup;
}
buffer = malloc(n * sizeof *buffer);
if (buffer == NULL) {
fprintf(stderr, "out of memory\n");
goto cleanup;
}
/* ... the actual work happens here ... */
status = 0; /* success */
cleanup:
free(buffer); /* free(NULL) is defined and harmless */
if (out != NULL) { fclose(out); }
if (in != NULL) { fclose(in); }
return status;
}
Compare it with the alternative. Without goto you either nest the success path four levels deep, or you repeat the release calls in every error branch — and repeated cleanup is precisely where leaks and double-frees come from.
Four rules make the pattern safe. Initialise every handle to NULL or -1 before the first possible jump, so the cleanup block can tell what was acquired. Release in reverse order of acquisition. Use exactly one label per function. And set status to success only at the very end, so any early jump reports failure by default.
Common Mistakes
continuein awhileloop whose increment sits at the bottom of the body. The counter never advances and the program hangs. Convert to aforloop or move the increment above thecontinue.- Expecting
breakto leave two nested loops. It leaves one. Use a flag, a forwardgoto, or extract a function andreturn. - Using
breakinside aswitchto escape the surrounding loop. Theswitchswallows it. This bug is invisible on inspection because the code looks exactly right. - Forgetting
breakbetweenswitchcases. Falling through is legal, so the compiler stays quiet unless you enable-Wimplicit-fallthrough. - Jumping forward over an initialisation.
goto skip;pastint n = compute();leavesnindeterminate, and reading it afterwards is undefined behaviour. - Putting a label at the very end of a function with nothing after it.
cleanup: }does not compile before C23. Add;or areturn. - A cleanup block that releases handles which were never acquired. If
inis uninitialised rather thanNULL,fclose(in)in the cleanup path is a crash. - Scattering
breakandcontinuethrough a long body. Once a loop has five exit points, no reader can tell what state holds at the bottom. Split it into functions.
Best Practices
- Use
continueas a guard clause at the top of a loop body to skip uninteresting items. It flattens nesting and reads well: "not a multiple of three, next". - Prefer folding a
breakcondition into the loop test when it is genuinely part of the loop's purpose. Keepbreakfor the exceptional exit. - Turn any nested search into a function that
returns. It is shorter, it names the operation, and it sidesteps the one-levelbreaklimit. - Restrict
gototo forward jumps to a single cleanup label. Never jump backwards, and never have two labels doing different cleanup in one function. - Initialise every file handle, pointer and descriptor to
NULLor-1at declaration, before any code that could jump to cleanup. - Release resources in reverse order of acquisition, and lean on the fact that
free(NULL)is explicitly safe. - Default your status variable to failure and set it to success as the last statement before the label. Then no error path can accidentally report success.
- Keep at most one
breakand onecontinueper loop. If you need more, the loop is doing more than one job.
Practice Exercises
- Primality, twice. Write a function that decides whether a number is prime using a loop with
break, then rewrite it with nobreakat all by folding the condition into the loop test. Confirm both agree for every value from 1 to 100. - Guard clauses. Read up to 20 integers and total only the positive even ones, using
continueto reject the rest at the top of the body. Then rewrite the body as a singleifand note which version you find easier to extend with a third condition. - Escaping two loops, three ways. Search a 5 by 5 grid for a target value and report its row and column, once with a flag, once with a forward
goto, and once by extracting a function thatreturns. Verify all three find the same cell, and write two sentences on which you would submit for review. - A cleanup ladder of your own. Write a function that opens an input file, opens an output file and allocates a buffer, with a single
cleanuplabel. Force each failure in turn by passing a missing input path, an unwritable output path and an absurd allocation size, and confirm in each case that only the resources actually acquired are released.