Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 182 ยท Operators and Control Flow

break, continue, goto and return

Learn the C# jump statements - break, continue, return, throw and goto with labels - and the best ways to leave nested loops, plus common traps such as break inside a switch.

Normally a program runs one statement after another. Conditions and loops bend that order, and jump statements bend it further: they transfer control somewhere else immediately. C# has five of them: break, continue, return, throw and goto. Each has a precise job, and knowing which one fits keeps your loops short and your methods easy to read.

This lesson explains each statement with runnable examples, shows the common ways to leave several nested loops at once, explains why goto is rare but not forbidden, and lists the traps, such as a break that only leaves a switch. Make sure you know the loops from while, do-while and for and foreach.

break: leave the loop

break ends the nearest enclosing loop (for, foreach, while, do) or switch and continues with the statement after it. The classic use is searching: once you have found what you want, there is no reason to keep looking.

C# Stop searching when found

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 Console.ReadLine()), it gets the next line from this box.

The loop stops after 14, so 7, 21 and 5 are never checked. For simple searches LINQ's FirstOrDefault or Any is shorter, but a loop with break stays useful when the body does more than compare.

continue: skip to the next pass

continue ends the current pass and jumps to the next one. In a for loop the iterator (i++) still runs; in a while loop control goes back to the condition. Use it to skip items that should not be processed, which avoids wrapping the whole body in an if.

C# Skip invalid items with continue

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 Console.ReadLine()), it gets the next line from this box.

Each continue is a guard clause for the loop body, the same idea as in if and else. The remaining statements form the happy path with no extra indentation.

Be careful with continue in a while loop: if the counter is incremented at the bottom of the body, skipping past it creates an infinite loop.

C# continue skips the increment (infinite loop, stopped by a guard)

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 Console.ReadLine()), it gets the next line from this box.

Without the extra guard, this loop would never finish. A for loop avoids the problem because its iterator runs on continue.

return: leave the method

return ends the whole method at once, optionally with a value. Because it exits all loops on the way out, it is the cleanest way to leave nested loops when the work happens in a method.

C# Finding a pair, leaving two loops with return

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 Console.ReadLine()), it gets the next line from this box.

The method returns a nullable tuple: the pair when found, null otherwise. The return inside the inner loop exits both loops and the method in one step. In a method that returns void, write a bare return;.

A return inside a try block still runs the finally block first:

C# return and finally

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 Console.ReadLine()), it gets the next line from this box.

The output order is working..., cleanup always runs, then result.

throw: jump to a handler

throw raises an exception and unwinds the call stack until a matching catch is found. It is a jump with a very long reach: it can leave loops, methods and several callers. Use it for errors, not for ordinary control flow, because exceptions are slow compared with break or return, and surprising to readers.

C# throw leaves loops and methods

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 Console.ReadLine()), it gets the next line from this box.

10 and 20 are processed, then the exception jumps out of foreach and Process into the catch; 30 is never reached. The full story is in exceptions.

Leaving nested loops

break and continue affect only the innermost loop. A very common mistake is to expect break to leave both loops:

C# break only leaves the inner loop

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 Console.ReadLine()), it gets the next line from this box.

You get three lines, one per row. There are four good ways to leave all the loops:

  1. Move the loops into a method and return. This is usually the best option: it also gives the search a name (see FindPairWithSum above).
  2. A flag variable that the outer loop checks.
  3. goto with a label placed after the loops.
  4. Rewrite with LINQ (Any, FirstOrDefault) when the logic is a simple search.
C# Flag versus 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 Console.ReadLine()), it gets the next line from this box.

goto and labels

goto label; jumps to a statement marked with a label (label:). C# restricts it in sensible ways: you may jump out of a block to a label in an enclosing scope, but you cannot jump into a block, and you cannot jump out of a finally block. Two special forms exist in switch statements, goto case value; and goto default;, covered in switch.

Why is goto rare? Because jumping around makes the flow hard to follow. Code that uses it heavily becomes the "spaghetti" that structured programming was invented to avoid. There are, however, a few cases where it is accepted: leaving deeply nested loops at once, retrying from the top of a method, and state machines in generated code. If you use it, keep the label close and its name meaningful (done, retry).

C# A retry label

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 Console.ReadLine()), it gets the next line from this box.

The second attempt succeeds. A while loop with a counter would express the same thing and is almost always clearer, which is the usual verdict on goto.

Labels can also produce warnings when unused: a label that no goto targets triggers warning CS0164: This label has not been referenced, so delete them when they are no longer needed.

Traps and style notes

  • break inside switch inside a loop leaves only the switch, not the loop. To leave the loop, use return, a flag or goto. A frequent bug in menu loops.
  • Unreachable code. Statements after an unconditional break, continue, return or throw never run; the compiler warns with CS0162 ("Unreachable code detected").
  • break is not allowed outside loops and switches, and continue only works in loops. Using either elsewhere is a compile error.
  • Prefer early exits to deep nesting, but do not put continue or break in the middle of long, complicated loop bodies where the reader will miss them. If a body needs five continue statements, extract a method.
  • Lambdas and local functions have their own scope. A break or return inside a lambda ends the lambda, not the outer method.
C# Unreachable code and a break in 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 Console.ReadLine()), it gets the next line from this box.

All four passes run (the break ended the switch only), and the compiler prints warning CS0162: Unreachable code detected for the last line of Describe.

When you reach for goto or a flag to escape nested loops, first ask whether the loops should be their own method. A method named FindFirstMatch that returns early is clearer than any trick.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A break statement sits inside an inner for loop that is inside an outer for loop. What does it do?

    break affects the nearest enclosing loop or switch. To leave both loops use return, a flag or goto.
  2. 2. What is the difference between break and continue?

    break leaves the loop completely. continue abandons the rest of the current pass and starts the next one.
  3. 3. Which is usually the cleanest way to leave several nested loops once a result is found?

    A return leaves all loops and gives the search a name. Exceptions are for errors, and counter tricks are hard to read.
  4. 4. What happens when a return statement runs inside a try block that has a finally block?

    finally blocks run on every exit from the try block, including return.
  5. 5. Which goto usage does C# NOT allow?

    You can jump out of blocks to a label in an enclosing scope, but never into a block.

Summary

  • break leaves the nearest loop or switch; continue skips to the next pass of the nearest loop.
  • return leaves the method and every loop inside it; it is the best way to exit nested loops when you can extract a method.
  • throw jumps to the nearest matching catch; use it for errors rather than ordinary flow.
  • goto label; works inside the same method and cannot jump into a block; it is rare, but acceptable for escaping deep nesting or retrying.
  • A break inside a switch inside a loop only leaves the switch.
  • Code after an unconditional jump is unreachable and the compiler warns about it.

Next: Ranges and Indices