Break
C programming, the `break` statement is used to exit a loop or switch statement prematurely. When encountered, the `break` statement immediately terminates the innermost loop or switches the control flow out of the switch statement.
The usage of the `break` statement differs slightly between loops and switch statements.
1. In Loops:
The `break` statement is commonly used within loops (such as `for`, `while`, or `do-while`) to exit the loop before its normal termination condition is met. It allows you to break out of the loop based on a certain condition.
Here's an example illustrating the use of `break` in a `while` loop:
#include <stdio.h>
int main() {
int i = 1;
while (i <= 10) {
printf("%d\n", i);
if (i == 5) {
break; // Exit the loop when i equals 5
}
i++;
}
printf("Loop complete.\n");
return 0;
}
In this example, the `break` statement is encountered when `i` is equal to 5. As a result, the loop is prematurely exited, and the program proceeds to execute the statement after the loop. The output will be the numbers 1 to 5 printed on separate lines, followed by "Loop complete."
The `break` statement can be particularly useful when you need to terminate a loop based on a specific condition, regardless of the loop's regular termination condition.
2. In Switch Statements:
The `break` statement is also used within `switch` statements to exit the switch block. After executing the code block of a particular `case`, the `break` statement is used to prevent the flow of control from falling through to subsequent cases.
Here's an example demonstrating the use of `break` in a `switch` statement:
#include <stdio.h>
int main() {
int choice = 2;
switch (choice) {
case 1:
printf("Option 1\n");
break;
case 2:
printf("Option 2\n");
break;
case 3:
printf("Option 3\n");
break;
default:
printf("Invalid option\n");
}
printf("Switch complete.\n");
return 0;
}
In this example, when `choice` is 2, the corresponding case is executed, printing "Option 2." After executing the code block, the `break` statement is encountered, causing the switch statement to exit. The output will be "Option 2" followed by "Switch complete."
Without the `break` statement, the control flow would fall through to subsequent cases, executing their code blocks as well. Using `break` is crucial to ensure that only the desired case is executed in a switch statement.
Both in loops and switch statements, the `break` statement allows you to control the flow of execution and exit the construct prematurely based on specific conditions.