Examples Using the break Statement

The following example shows a break statement in the action part of a for statement. If the ith element of the array string is equal to '\0', the break statement causes the for statement to end.

for (i = 0; i < 5; i++)
{
   if (string[i] == '\0')
      break;
   length++;
}

The following is an equivalent for statement, if string does not contain any embedded null characters:

for (i = 0; (i < 5)&& (string[i] != '\0'); i++)
{
   length++;
}

The following example shows a break statement in a nested iterative statement. The outer loop goes through an array of pointers to strings. The inner loop examines each character of the string. When the break statement is processed, the inner loop ends and control returns to the outer loop.

/**
 **  This program counts the characters in the strings that are
 **  part of an array of pointers to characters.  The count stops
 **  when one of the digits 0 through 9 is encountered
 **  and resumes at the beginning of the next string.
 **/
 
#include <stdio.h>
#define  SIZE  3
 
int main(void)
{
   static char *strings[SIZE] = { "ab", "c5d", "e5" };
   int i;
   int letter_count = 0;
   char *pointer;
 
   for (i = 0; i <SIZE; i++) /* for each string */ 
                             /* for each character */ 
       for (pointer=strings[i]; *pointer != '\0' ; ++pointer)
       {                     /* if a number */ 
           if (*pointer >='0' && *pointer <= '9' ) 
               break; 
           letter_count++;
       }
   printf("letter count="%d\n"," letter_count);
}

The program produces the following output:

letter count = 4

The following example is a switch statement that contains several break statements. Each break statement indicates the end of a specific clause and ends the switch statement.

#include <stdio.h>
 
enum {morning, afternoon, evening} timeofday = morning;
 
int main(void) {
 
   switch (timeofday) {
      case (morning):
         printf("Good Morning\n");
         break;
 
      case (evening):
         printf("Good Evening\n");
         break;
 
      default:
         printf("Good Day, eh\n");
   }
}


break Statement