break语句用于循环内部和switch case 。
C - break语句
它用于立即退出循环。当在循环内遇到break语句时,控制流直接退出循环并且循环终止。它与if语句一起使用,只能在循环内使用。
这也可用于switch-case控制结构。每当在switch-case中遇到它时,控制器都会从switch-case中出来(参见下面的例子)。
break语句的流程图

语法:
break;
示例 - 在while循环中使用break
#include <stdio.h>int main(){int num =0;while(num<=100){printf("value of variable num is: %d\n", num);if (num==2){break;}num++;}printf("Out of while-loop");return 0;}
输出:
value of variable num is: 0value of variable num is: 1value of variable num is: 2Out of while-loop
示例 - 在for循环中使用break
#include <stdio.h>int main(){int var;for (var =100; var>=10; var --){printf("var: %d\n", var);if (var==99){break;}}printf("Out of for-loop");return 0;}
输出:
var: 100var: 99Out of for-loop
示例 - 在switch-case中使用break语句
#include <stdio.h>int main(){int num;printf("Enter value of num:");scanf("%d",&num);switch (num){case 1:printf("You have entered value 1\n");break;case 2:printf("You have entered value 2\n");break;case 3:printf("You have entered value 3\n");break;default:printf("Input value is other than 1,2 & 3 ");}return 0;}
输出:
Enter value of num:2You have entered value 2
您总是希望在switch case块中使用break语句,否则一旦执行了case块,其余的后续 case 块就会执行。例如,如果我们不在每个case块之后使用break语句,那么这个程序的输出将是:
Enter value of num:2You have entered value 2You have entered value 3Input value is other than 1,2 & 3
