在C语言中,continue
关键字的用法有以下几种:
continue
语句用于跳过当前迭代中剩余的语句,并进入下一次迭代。它通常与for
、while
和do-while
循环一起使用。示例:
for (int i = 0; i < 10; i++) {if (i == 5) {continue; // 当i等于5时跳过剩余语句,进入下一次迭代}printf("%d ", i);}
输出结果:0 1 2 3 4 6 7 8 9
continue
语句还可以用于跳过外层循环的当前迭代,进入内层循环的下一次迭代。示例:
for (int i = 1; i <= 3; i++) {for (int j = 1; j <= 3; j++) {if (j == 2) {continue; // 当j等于2时跳过内层循环的剩余语句,进入下一次迭代}printf("%d %d\n", i, j);}}
输出结果:
1 11 32 12 33 13 3
在switch
语句中使用:continue
语句常用于switch
语句中,用于跳过当前case
块的剩余语句,进入下一个case
块。示例:
int num = 2;switch (num) {case 1:printf("This is case 1\n");break;case 2:printf("This is case 2\n");continue; // 跳过当前case块的剩余语句,进入下一个case块case 3:printf("This is case 3\n");break;default:printf("This is default case\n");break;}
输出结果:This is case 2
需要注意的是,continue
关键字只能在循环语句中使用,不能在函数或其他非循环结构中使用。