C Programming Tutorial
The break statement terminates the execution of the nearest enclosing do, for, switch, or while statement in which it appears. Control passes to the statement that follows the terminated statement.
Syntax
jump-statement:
break;
Flowchart of break in c
The break statement is frequently used to terminate the processing of a particular case within a switch statement. Lack of an enclosing iterative or switch statement generates an error.
Within nested statements, the break statement terminates only the do, for, switch, or while statement that immediately encloses it. You can use a return or goto statement to transfer control elsewhere out of the nested structure.
This example illustrates the break statement:
#include <stdio.h>
int main() {
char c;
for(;;) {
printf_s( "\nPress any key, Q to quit: " );
// Convert to character value
scanf_s("%c", &c);
if (c == 'Q')
break;
}
}
Loop exits only when 'Q' is pressed
Example of C break statement with loop
#include<stdio.h>
int main(){
int i=1;//initializing a local variable
//starting a loop from 1 to 10
for(i=1;i<=10;i++){
printf("%d \n",i);
if(i==5){//if value of i is equal to 5, it will break the loop
break;
}
}
return 0;
}
Output
1
2
3
4
5
As you can see on console output, loop from 1 to 10 is not printed after i==5.
C break statement with inner loop
In such case, it breaks only inner loop, but not outer loop.
#include<stdio.h>
int main(){
int i=1,j=1;//initializing a local variable
for(i=1;i<=3;i++){
for(j=1;j<=3;j++){
printf("%d &d\n",i,j);
if(i==2 && j==2){
break;//will break loop of j only
}
}
return 0;
}
Output
1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3
As you can see the output on console, 2 3 is not printed because there is break statement after printing i==2 and j==2. But 3 1, 3 2 and 3 3 is printed because break statement works for inner loop only.