温馨提示×

c语言continue的用法有哪些

小亿
157
2023-08-26 05:13:27
栏目: 编程语言

在C语言中,continue关键字的用法有以下几种:

  1. 在循环语句中使用:continue语句用于跳过当前迭代中剩余的语句,并进入下一次迭代。它通常与forwhiledo-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

  1. 在嵌套循环中使用: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 1
1 3
2 1
2 3
3 1
3 3
  1. 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关键字只能在循环语句中使用,不能在函数或其他非循环结构中使用。

0