1. Technology

C Tutorial - Lesson Five - About Control Statements

By

3 of 5

Break and Continue
These two words apply to all the loop types, i.e. while, for and do. Each behave differently.

Break

Break forces a loop to exit immediately. Here's an example:

int markerpos=-1;
for (index=0 ;index < 10;index++ )
{
if (values[index] ==-999 )
{
markerpos = index;
; break;
}
}
if (markerpos== 999)
printf("-1 Not located in array";
else
printf("-1 Found at index %i\n\r",markerpos) ;

That's a more complicated example. It searches the 10 element array values looking for a 999 value. The variable markerpos holds the position if a 999 is found. It is initialized to -1 and after the search this value is examined to see if a 999 was found.

Continue

This does the opposite of break; Instead of terminating the loop, it immediately loops again, skipping the rest of the code. So lets sum that integer array again, but this time we'll leave out elements with an index of 4 and 5.

int value =0;
for (index=0 ;index < 10;index++ )
{
if (index==4 || index==5)
continue;
value += numbers[index];
}
printf("Value = %i",value) ;

You probably won't use continue very often but it's useful on the odd occasion.

On the next page : Learn about the while and do while statements.

See More About
  1. About.com
  2. Technology
  3. C / C++ / C#
  4. C Programming
  5. C Tutorials
  6. Break and Continue - C Tutorial - Lesson Five

©2014 About.com. All rights reserved.