How to break a for loop in C and Objective-C

Did you know that we can break out of a for loop before it finishes? It’s true – and it works with both regular for loops, as well as fast enumeration (for…in loops). And we can do it in either of two ways.

Let’s imagine we have an array with one thousand words. We’re only interested in finding a single one, and at that point we want to stop the loop.

Breaking with the break statement

The break statement will get us out of a for loop and continue programme execution after the finishing bracket of the loop. Here’s an example with a regular for loop:

The break statement also works with fast enumeration:

Breaking with “goto label”

Goto sounds like an old BASIC command – and we can still use it in Objective C. It doesn’t work on its own though and needs an arbitrary label to which we can direct the loop after we’ve broken from it.

Here’s how we might do this with a regular for loop:

Notice that when we declare the label where we’d like the programme to continue, we must do so with a colon (and a semi colon to finish the line).

The same principle also works with fast enumeration:

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.