The break keyword

The break keyword can be used in two ways. Either inside a switch block to exit the block, or in a loop. Here I’ll just focus on the second case, the first one being mandatory anyway when using a switch. When you create a loop, you may sometimes want to exit it before all occurences are finished under some conditions. This is where the break keyword comes into action. This code line will indeed allow us to exit the loop immediately and continue with the first line that follows. Let’s analyze the following example: I create a for loop from 0 to 9 but I want to exit it when my counter reaches 5 (yeah yeah I know it’s stupid but I prefer a case study for such simple lesson J). At each iteration, I just display the counter value (Figure 1).

break

Figure 1

We can see that the break keyword is self-sufficient, it is a code line on its own. We thus have our loop in which we display the counter value. But when it equals 5, we want to exit the loop. Let’s see the result displayed by this method (Figure 2).

break-result

Figure 2

The counter indeed stops getting displayed when it reaches 5, meaning that we correctly get out of the loop when the condition is met. I’ll soon publish another post about the continue keyword which is also used within loops but with behaves differently.

Advertisements