The break Statement

The previous section explained how to use break to exit from a switch statement. You can also use break to end a loop immediately. The BREAKER.C program shows how to do this. The program prints a prompt, then displays characters as they are typed until you type a number and press ENTER.

/* BREAKER.C: Demonstrate break statement. */

#include <stdio.h>

#include <ctype.h>

main()

{

char ch;

printf( "Type any letter. Or type a number and press Enter to quit.\n" );

while( 1 )

{

ch = getchar();

if( isdigit(ch) )

{

printf( "\nYou typed a number\n" );

break;

}

}

}

The while statement in BREAKER.C creates an indefinite loop that calls the getchar function again and again, assigning the function's return value to the variable ch. The if statement in the loop body calls the isdigit library function to determine if the character you type is a numeric digit. When you type a number and press ENTER, BREAKER.C prints You typed a number and executes the break statement, which terminates the while loop and ends the program.

Summary: A break statement exits only one loop.

It's important to remember that the break statement only ends the loop in which it appears. If two loops are nested, executing a break in the inner loop exits that loop but not the outer loop. BREAKER1.C shows how break works within nested loops. The program's inner loop checks for the T key and the outer loop checks for a number key.

/* BREAKER1.C: Break only exits one loop. */

#include <stdio.h>

#include <ctype.h>

main()

{

char ch;

printf( "Type any letter. Type a number and Enter to quit.\n" );

do

{

while( !( isdigit(ch = getchar() ) ) )

{

if( (ch == 'T') || (ch == 't') )

{

printf( "\nYou typed T\n" );

break;

}

}

} while( !(isdigit(ch)));

printf( "\nBye bye." );

}

The BREAKER1.C program includes a while loop nested within a do loop. Both loops test the same condition—whether the variable ch equals a numeric digit. The while loop also calls the getchar function, assigning the function's return value to ch.

When T is typed, the program prints You pressed T and executes a break statement, which terminates the inner loop. The break does not end the outer loop, however. The program continues until you type a number and press ENTER, providing the condition that ends both loops.

Note that break can only be used to exit a loop or switch statement. While you might be tempted to use break to jump out of complex if or else statements, the break statement cannot be used for this purpose. It has no effect on if and else.