在C语言中我们常会使用break、continue,
这篇博文主要是写,在for循环中break和continue的作用和区别;
continue
#include <stdio.h>int count = 0;int main(int argc, char *argv[]){for (int i = 0; i < 6; i++, count++, printf("count = %dn", count)) { if (i == 2) { printf("i = %dn", i); continue; } printf("1111111"); } return 0;}运行结果:
bao:day1015 bao$ gcc -o test2 test2.c
bao:day1015 bao$ ./test2
1111111count = 1
1111111count = 2
i = 2
count = 3
1111111count = 4
1111111count = 5
1111111count = 6
通过运行结果,我们可以得出
1、continue在for循环中的作用是跳出本次循环,进行下一次循环;
2、如果在for调用continue,那么for循环中continue后面的代码不进行作用(printf("1111111"); 不执行),
但是for循环中的i++, count++, printf("count = %dn", count)还是会执行.
break
#include <stdio.h>int count = 0;int main(int argc, char *argv[]){for (int i = 0; i < 6; i++, count++, printf("count = %dn", count)) { if (i == 2) { printf("i = %dn", i); break; } printf("1111111"); } return 0;}运行结果
bao:day1015 bao$ ./test2
1111111count = 1
1111111count = 2
i = 2
1、break会跳出循环,不会执行break后面的一切代码.