亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> C语言

掌握 C++ continue 语句:跳过当前迭代的循环控制艺术

C++ continue 语句完全指南

详解 C++ continue 语句在 for/while/嵌套循环中的“跳过本轮、进入下轮”行为,附完整可运行示例。

C++ 中 continue 关键字指示循环跳过当前迭代剩余代码,直接进入下一轮条件判断(for 循环则执行 update 表达式)。

语法:

continue;

前置知识:for 循环、if/else、while 循环。


continue 运作原理

掌握 C++ continue 语句:跳过当前迭代的循环控制艺术

示例 1:for 循环中 continue

for 循环中 continue 跳过当前迭代,直接执行 update 表达式。

#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 5; ++i) {
        if (i == 3) {
            continue;  // 跳过 i==3 的打印
        }
        cout << i << endl;
    }
    return 0;
}

输出

1
2
4
5

解析:

技巧:continue 最适合配合条件判断,实现“过滤式”循环。

示例 2:while 循环中 continue

while 循环中 continue 直接跳回条件判断。

#include <iostream>
using namespace std;

int main() {
    int sum = 0, number = 0;
    while (number >= 0) {
        sum += number;  // 累加非负数
        cout << "Enter a number: ";
        cin >> number;
        if (number > 50) {
            cout << "The number is greater than 50 and won't be calculated." << endl;
            number = 0;  // 重置以继续提示
            continue;    // 跳过本轮后续(此处无后续,但演示语义)
        }
    }
    cout << "The sum is " << sum << endl;
    return 0;
}

示例运行

Enter a number: 12
Enter a number: 0
Enter a number: 2
Enter a number: 30
Enter a number: 50
Enter a number: 56
The number is greater than 50 and won't be calculated.
Enter a number: 5
Enter a number: -3
The sum is 99

关键点:

注意:do...while 同理适用。

嵌套循环中的 continue

规则:continue 仅影响直接包裹它的最内层循环。

#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 3; ++i) {
        for (int j = 1; j <= 3; ++j) {
            if (j == 2) {
                continue;  // 跳过 j==2 的本轮
            }
            cout << "i = " << i << ", j = " << j << endl;
        }
    }
    return 0;
}

输出

i = 1, j = 1
i = 1, j = 3
i = 2, j = 1
i = 2, j = 3
i = 3, j = 1
i = 3, j = 3

内层 j==2 时 continue 跳过该迭代,直接进入 j=3。

对比:break 退出整个循环;continue 仅跳过当前迭代。

实战模式:continue 实现“卫语句”风格循环

for (auto& item : items) {
    if (!item.IsValid()) continue;      // 早期过滤
    if (item.IsProcessed()) continue;   // 跳过已处理
    if (item.RequiresAdmin() && !currentUser.IsAdmin()) continue; // 权限过滤

    // 核心业务逻辑:扁平、无嵌套
    Process(item);
}

这种“卫语句”风格让主逻辑保持左对齐,极大提升可读性。

C语言

  1. 掌握 C# 条件逻辑:if、if-else、if-else if 与嵌套 if 语句完全指南
  2. 掌握 C# switch 语句:语法、示例与最佳实践
  3. C# break 语句:用法、时机与实战示例
  4. 掌握 C# continue 语句:高效跳过循环迭代的实战指南
  5. 深入理解 C++ 类型转换:隐式、显式转型与现代 Cast 算符
  6. 掌握 C++ 运算符:六大类型全解析与实战示例
  7. C++ 注释最佳实践:编写可读、可维护代码的注释艺术
  8. 掌握 C++ 条件语句:if、if-else、嵌套 if 与多重分支全解析
  9. C++ while 与 do-while 循环:重复控制流完全掌握
  10. 掌握 C++ break 语句:跳出循环与 switch 的核心控制流
  11. C++ 类模板实战指南:编写灵活的类型无关代码
  12. 掌握 C++ switch-case:语法、用法与实战示例