break statement in Objective-C

Advertisements

The break statement in Objective-C programming language has the following two usages:

  1. When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.

  2. It can be used to terminate a case in the switch statement (covered in the next chapter).

If you are using nested loops (i.e., one loop inside another loop), the break statement will stop the execution of the innermost loop and start executing the next line of code after the block.

Syntax:

The syntax for a break statement in Objective-C is as follows:

break;

Flow Diagram:

c break statement

Example:

#import <Foundation/Foundation.h>
 
int main ()
{
   /* local variable definition */
   int a = 10;

   /* while loop execution */
   while( a < 20 )
   {
      NSLog(@"value of a: %d\n", a);
      a++;
      if( a > 15)
      {
         /* terminate the loop using break statement */
          break;
      }
   }
 
   return 0;
}

When the above code is compiled and executed, it produces the following result:

2013-09-07 22:15:46.905 demo[12282] value of a: 10
2013-09-07 22:15:46.906 demo[12282] value of a: 11
2013-09-07 22:15:46.906 demo[12282] value of a: 12
2013-09-07 22:15:46.906 demo[12282] value of a: 13
2013-09-07 22:15:46.906 demo[12282] value of a: 14
2013-09-07 22:15:46.906 demo[12282] value of a: 15


Advertisements
Advertisements