C語言
for循環break、continue
在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 = %d\n", count)) {
if (i == 2) {
printf("i = %d\n", 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 = %d\n", count)
還是會執行.
break
#include <stdio.h>
int count = 0;
int main(int argc, char *argv[]){
for (int i = 0; i < 6; i++, count++, printf("count = %d\n", count)) {
if (i == 2) {
printf("i = %d\n", i);
break;
}
printf("1111111");
}
return 0;
}
運作結果
bao:day1015 bao$ ./test2
1111111count = 1
1111111count = 2
i = 2
1、break會跳出循環,不會執行break後面的一切代碼.