The Break and Continue Statements



The Break Statement

The break statement, when executed in a while, for, do while or switch statement, causes an immediate exit from that statement.

Program execution continues with the next statement. Common uses of the break statement are to escape early from a loop or to skip the remainder of a switch statement.


    // Using the break statement in a for statement
    #include <stdio.h>
    
    // function main begins program execution
    int main( void )
        {
     int a; // counter
   
    // loop 10 times
     for ( a = 1; a <= 10; ++a ) {
    
    // if a is 5, terminate loop
    if ( a == 5 ) {
         break; // break loop only if a is 5
        } // end if
      printf( "%d ", a ); // display value of a
     } // end for
   
    printf( "\nEnd of loop at a == %d\n", a );
    } // end function main

    Output:
    1 2 3 4
    End of loop at a = 5

Continue Statement

The continue statement, when executed in a while, for or do while statement, skips the remaining statements in the body of that control statement and performs the next iteration of the loop.

In while and do while statements, the loop-continuation test is evaluated immediately after the continue statement is executed. In the for statement, the increment expression is executed, then the loop-continuation test is evaluated.

   
    // Using the continue statement in a for statement
    #include <stdio.h>
    
    // function main begins program execution
    int main( void )
    {
     unsigned int a; // counter
    
    // loop 10 times
     for ( a = 1; a <= 10; ++a ) {
    
    // if a is 5, continue with next iteration of loop
      if ( a == 7 ) {   
         continue; // skip remaining code in loop body
      } // end if
      printf( "%u ", a ); // display value of a
    } // end for
   
      puts( "\nUsed continue to skip printing the value 7" );
    } // end function main

    Output:
    1 2 3 4 5 6 8 9 10
    Used continue to skip printing the value 7

Ads Right