C break
Statement
Syntax
The break
statement can be used in multiple ways as follows:
break;
Example
#include <stdio.h>
int main() {
int i;
for (i = 0; i < 10; i++) {
if (i == 5)
break;
printf("%d ", i);
}
return 0;
}
Output
0 1 2 3 4
Explanation
The break
statement in C is used to exit the current loop. When the break statement is encountered within a loop, the loop is immediately terminated and the program continues executing the next statement after the loop.
In the above example, the for
loop iterates 10 times. When i
becomes 5, the break
statement is executed, and the loop is terminated. The program then continues executing the next statement after the loop, which is the return statement.
Use
The break
statement can be used when you want to exit a loop based on a certain condition without going through all of the remaining iterations.
The break
statement is often used in loop constructs such as for
, while
, and do-while
.
Important Points
- The
break
statement can only be used within a loop construct. - When the
break
statement is executed, the loop is immediately terminated. - If there are multiple nested loops, the
break
statement will only terminate the innermost loop. - The
break
statement can be used with a label to break out of multiple nested loops at once.
Summary
The break
statement is a useful control statement in C used to exit a loop based on a certain condition. When the break
statement is encountered within a loop, the loop is immediately terminated, and the program continues executing the next statement after the loop. The break
statement can only be used within a loop construct and is often used with labeled statements to break out of multiple nested loops at once.