C语言中,break和continue都是跳出循环,有啥区别?
扫描二维码
随时随地手机看文章
对于 for 循环,执行 continue 之后的下一个行为是对更新表达式求值,然后是对循环测试表达式求值,下面的代码示例包括了嵌套循环中使用 continue 的情形:#include int main() { //while() char CH; int count=0; while(count < 10){ CH = getchar(); if(CH != ' ') continue; putchar(CH); count++; } printf("Hello, World!\n"); return 0; }
continue跳出本次循环,执行下一次循环。
break:
break跳出整个循环
下面看代码 while 示例:for循环及嵌套循环示例: 注:只会直接跳出内层循环,外层循环正常执行#include int main() { //while() char CH; int count=0; while(count < 10){ CH = getchar(); if(CH != ' ') break; putchar(CH); count++; } printf("Hello, World!\n"); return 0; }
要想外层循环一并终止;需要在外层在使用 break;#include int main() { char ch; int cunt; int i; for(cunt=0;cunt<10;cunt++){ ch = getchar(); for(i=0;i<5;i++){ if (ch != ' ') break; putchar(ch); printf("我是内层循环的---小可爱!!!\n"); } printf("我是外层循环的---小可爱!!!\n"); printf("如果continue语句在嵌套循环内,则只会影响包含continue的内层循环,不影响外层循环!!!\n"); } printf("Hello, World!\n"); return 0; }
在多重选择 switch 语句中使用 continue 和 break的示例:#include int main() { char ch; int cunt; int i; for(cunt=0;cunt<10;cunt++){ ch = getchar(); for(i=0;i<5;i++){ if (ch != ' ') break; putchar(ch); printf("我是内层循环的---小可爱!!!\n"); } if (ch != ' ') break; printf("我是外层循环的---小可爱!!!\n"); printf("如果continue语句在嵌套循环内,则只会影响包含continue的内层循环,不影响外层循环!!!\n"); } printf("Hello, World!\n"); return 0; }
在本例中 continue 的作用与上述类似,但是 break 的作用不同:它让程序离开 switch 语句,跳至switch语句后面的下一条语句;如果没有 break 语句,就会从匹配标签开始执行到 switch 末尾; 注:C语言中的 case 一般都指定一个值,不能使用一个范围;switch 在圆括号中的测试表达式的值应该是一个整数值(包括 char 类型);case 标签必须是整数类型(包括 char 类型)的常量 或 整型常量表达式( 即, 表达式中只包含整型常量)。不能使用变量作为 case 的标签 switch中有 break/* animals.c -- uses a switch statement */ #include #include int main(void) { char ch; printf("Give me a letter of the alphabet, and I will give "); printf("an animal name\nbeginning with that letter.\n"); printf("Please type in a letter; type # to end my act.\n"); while ((ch = getchar()) != '#') { if('\n' == ch) continue; if (islower(ch)) /* lowercase only */ switch (ch) { case 'a' : printf("argali, a wild sheep of Asia\n"); break; case 'b' : printf("babirusa, a wild pig of Malay\n"); break; case 'c' : printf("coati, racoonlike mammal\n"); break; case 'd' : printf("desman, aquatic, molelike critter\n"); break; case 'e' : printf("echidna, the spiny anteater\n"); break; case 'f' : printf("fisher, brownish marten\n"); break; default : printf("That's a stumper!\n"); } /* end of switch */ else printf("I recognize only lowercase letters.\n"); while (getchar() != '\n') continue; /* skip rest of input line */ printf("Please type another letter or a #.\n"); } /* while loop end */ printf("Bye!\n"); return 0; }
遇到break后跳出,继续匹配switch。
switch 中 无break
顺序执行每个case。
免责声明:本文内容由21ic获得授权后发布,版权归原作者所有,本平台仅提供信息存储服务。文章仅代表作者个人观点,不代表本平台立场,如有问题,请联系我们,谢谢!