How to use the “break” statement in the C language?
In the C language, the break statement is used to terminate the execution of loop statements (such as for, while, do-while) or switch statements, and jump out of the code block of the loop or switch statement. The usage of the break statement is as follows:
- Using break in a loop statement:
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
printf("%d ", i);
}
The code will output: 0 1 2 3 4. When i equals 5, the break statement is executed and the loop ends.
- Use break in a switch statement.
int num = 2;
switch (num) {
case 1:
printf("Case 1");
break;
case 2:
printf("Case 2");
break;
case 3:
printf("Case 3");
break;
default:
printf("Default case");
}
The code above will output: Case 2. The switch statement will stop executing when num is equal to 2, as the break statement is executed after case 2.
It should be noted that the break statement can only be used within loops or switch statements, and cannot be used on its own or within other statements.