The break Statement
The break statement has two uses. You can use it to terminate a case in the switch statement. You can also use it to force immediate termination of a loop, bypassing the normal loop conditional test.
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. For example,
#include <stdio.h>int main(void)
{
int t;
for(t=0; t<100; t++) {
printf("%d ", t);
if(t==10) break;
}
return 0;
}
prints the numbers 0 through 10 on the screen. Then the loop terminates because break causes immediate exit from the loop, overriding the conditional test t<100.
Programmers often use the break statement in loops in which a special condition can cause immediate termination. For example, here a keypress can stop the execution of the look_up() function:
void look_up(char *name)
{
do {
/* look up names ... */
if(kbhit()) break;
} while(!found);
/* process match */
}
The kbhit() function returns 0 if you do not press a key. Otherwise, it returns a nonzero value. Because of the wide differences between computing environments, neither Standard C nor Standard C++ defines kbhit(), but you will almost certainly have it (or one with a slightly different name) supplied with your compiler.
A break causes an exit from only the innermost loop. For example,
for(t=0; t<100; ++t) {
count = 1;
for(;;) {
printf("%d ", count);
count++;
if(count==10) break;
}
}
prints the numbers 1 through 10 on the screen 100 times. Each time execution encounters break, control is passed back to the outer for loop.
A break used in a switch statement will affect only that switch. It does not affect any loop the switch happens to be in.