The break statement is a control flow statement used to exit from loops or switch statements prematurely. It provides a way to terminate the loop or switch block before its normal termination condition is met.
// Inside a loop or switch case
break;
The break statement can be used within for, while, and do-while loops to terminate the loop and transfer control to the statement immediately following the loop.
#include <stdio.h>
int main() {
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exit the loop when
i is 5
}
printf("i = %d\\n", i);
}
printf("Loop terminated.\\n");
return 0;
}
i = 0
i = 1
i = 2
i = 3
i = 4
Loop terminated.
#include <stdio.h>
int main() {
int count = 0;
while (1) { // Infinite loop
if (count == 3) {
break; // Exit the loop when
count is 3
}
printf("count = %d\\n", count);
count++;
}
printf("Loop terminated.\\n");
return 0;
}
count = 0
count = 1
count = 2
Loop terminated.
In a switch statement, the break statement is used to terminate a particular case and prevent the execution from falling through to subsequent cases.
#include <stdio.h>
int main() {
int day = 3;
switch (day) {
case 1:
printf("Monday\\n");
break;
case 2:
printf("Tuesday\\n");
break;
case 3:
printf("Wednesday\\n");
break;
case 4:
printf("Thursday\\n");
break;
case 5:
printf("Friday\\n");
break;
default:
printf("Weekend\\n");
break;
}
return 0;
}
Wednesday
• Scope of break: The break statement only affects the loop or switch block in which it is used.
• Termination of Execution: If a break statement is used within a switch statement, it stops the execution of that case block.
• Nested Loops: To exit from multiple nested loops, you might use additional logic or a flag variable.