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.
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.
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.
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.