Learn Objective-C: Loop Aids

In a loop, you can use the keywords continue; and break; to control the execution of the loop.

The continue Keyword

In a loop, continue tells the program to begin the next iteration, ignoring any code that comes after it. For example, if we had a simple program that reads in input and checks if the input is 5, we could use the following code:

  1. for (int times = 1; times <= 10; times++) {
  2.     int input;
  3.     scanf("%d", &input);
  4.     if (input != 5)
  5.         continue;
  6.     NSLog(@"Five!");
  7. }

In this loop, if the input is not 5, then the word “Five” is not printed. The program moves on to the next iteration of the loop.

33The break Keyword The break statement is used in the same context as continue, except that the break statement immediately ends the execution of the loop and moves on to the code after the loop. For example:

  1. for (int times = 1; times <= 10; times++) {
  2.     int input;
  3.     scanf("%d", &input);
  4.     if (input != 5)
  5.         break;
  6. }
  7. NSLog(@"Not Five!");

“Not Five” will be printed as soon as the user enters something that is not five.

Pitfalls

Keep in mind that continue and break only apply to the “closest” loop—that is, in the case of nested loops, they will only apply to the “deepest” loop.

This post is part of the Learn Objective-C in 24 Days course.

Author: Feifan Zhou