C Reference ยท Keywords and Statements
The break and continue statements
Reference for the C break and continue statements: leaving loops and switches early, skipping iterations, nested loops, and the usual traps.
break ends the nearest enclosing loop or switch immediately. continue abandons the rest of the current loop iteration and moves on to the next one. Both are jump statements that save you from nesting extra if blocks or from carrying a "done" flag around.
break works in for, while, do-while and switch. continue works only in loops. Neither can leave more than one level; for that you need a flag, a function return or goto.
for (int i = 0; i < n; i++) { if (skip(i)) continue; /* next iteration */ if (stop(i)) break; /* leave the loop */ work(i); }
Try it
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.
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.
Syntax
break ; continue ;
| Statement | Effect |
|---|---|
break; |
Transfers control to the statement after the nearest enclosing for, while, do or switch. |
continue; |
In a for loop jumps to the update expression, in while and do-while to the condition test. |
Errors: break outside a loop or switch and continue outside a loop are compile errors.
Usage notes
- One level only. In nested loops
breakleaves just the inner one. Use a flag, move the loops into a function andreturn, orgotoa label after the loops. breakinsideswitchinside a loop ends the switch, not the loop, which regularly surprises beginners.continuethere does affect the loop.continueinforstill runs the update clause, so the counter advances. In awhileloop you must update the variable yourself before thecontinue, or you create an infinite loop.- Readability. Early
continuefor "uninteresting" cases keeps the main logic unindented. Too many jumps in one loop are a sign that the body should become a function. - Not usable in a block that is only an
if.breakinside a plainifleaves the surrounding loop, not theif. - Cleanup that must run on every exit path does not belong after the loop only; with several
breaks, consider one exit point.
Related
for,whileanddo-while,switch,goto,return- Lessons: break, continue and goto