Skip to content

Break

The break statement is used to jump out of the current loop. As shown in the visualisation below, this is useful for ending a loop early.

The Break Statement allows you to end a loop early

Break — when, why, and how?

Sometimes you get part-way through a loop and know that the remainder of the loop’s code is not needed, and there is no need to check the loop’s condition again. If you can capture that in a condition, then combining a branching statement with a break will let you jump out of the loop.

This isn’t something you will use often, but is good to know exists.

In C

The break statement is simply the break keyword terminated with a semicolon.

How break works

Ending a loop early

The following code demonstrates the use of the break statement in an event driven program. Here the if statement checks whether the user has hit the escape key on their keyboard, and it breaks the event loop when that is true.

using static SplashKitSDK.SplashKit;
OpenWindow("Circle Test", 400, 400);
ClearScreen(ColorWhite());
while (!QuitRequested())
{
FillCircle(RandomColor(), Rnd(ScreenWidth()), Rnd(ScreenHeight()), Rnd(50));
RefreshScreen();
ProcessEvents();
if (KeyTyped(KeyCode.EscapeKey))
{
break; // end the loop
}
}

The following images show how this works.

Leaving intentionally infinite loops

You can create intentionally infinite loops, and use break statements within the code to terminate the loop. The following program uses an infinite loop, with a break in an if statement to terminate the loop.

using static System.Console;
using static System.Convert;
WriteLine("Before you stands a 12 foot tall Knight...");
WriteLine();
WriteLine("\"We are the Knights who say 'Ni'.\"");
WriteLine("\"I will say Ni to you again if you do not appease us!\"");
while(true)
{
WriteLine("\"Ni!\"");
Write("Submit? ");
if (ReadLine() == "y")
{
break;
}
}
WriteLine("\"Bring us a Shrubbery!\"");

The following images show how this works.

This example was inspired by the classic Monty Python sketch below. This comedy group was the inspiration behind the name for the Python programming language.