C++循环控制 #

一、break语句 #

1.1 基本作用 #

break语句用于立即跳出当前循环或switch语句。

1.2 在循环中使用 #

cpp
// 找到第一个能被7整除的数
for (int i = 1; i <= 100; i++) {
    if (i % 7 == 0) {
        std::cout << "找到: " << i << std::endl;
        break;  // 跳出循环
    }
}
// 输出:找到: 7

1.3 在while中使用 #

cpp
int i = 0;
while (true) {  // 无限循环
    std::cout << i << " ";
    i++;
    if (i >= 5) {
        break;  // 跳出循环
    }
}
// 输出:0 1 2 3 4

1.4 在switch中使用 #

cpp
int choice = 2;

switch (choice) {
    case 1:
        std::cout << "选项1" << std::endl;
        break;  // 跳出switch
    case 2:
        std::cout << "选项2" << std::endl;
        break;  // 跳出switch
    default:
        std::cout << "其他选项" << std::endl;
}

1.5 嵌套循环中的break #

cpp
// break只跳出最内层循环
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 5; j++) {
        if (j == 2) {
            break;  // 只跳出内层循环
        }
        std::cout << i << "," << j << " ";
    }
    std::cout << std::endl;
}
// 输出:
// 0,0 0,1
// 1,0 1,1
// 2,0 2,1

1.6 使用标志跳出多层循环 #

cpp
bool found = false;

for (int i = 0; i < 3 && !found; i++) {
    for (int j = 0; j < 5 && !found; j++) {
        if (i == 1 && j == 2) {
            found = true;
            break;
        }
        std::cout << i << "," << j << " ";
    }
}

二、continue语句 #

2.1 基本作用 #

continue语句跳过当前迭代的剩余部分,直接进入下一次迭代。

2.2 在for循环中使用 #

cpp
// 打印1到10中的奇数
for (int i = 1; i <= 10; i++) {
    if (i % 2 == 0) {
        continue;  // 跳过偶数
    }
    std::cout << i << " ";
}
// 输出:1 3 5 7 9

2.3 在while循环中使用 #

cpp
int i = 0;
while (i < 10) {
    i++;
    if (i % 2 == 0) {
        continue;  // 跳过偶数
    }
    std::cout << i << " ";
}
// 输出:1 3 5 7 9

2.4 过滤数据 #

cpp
// 只处理正数
int arr[] = {-2, 5, -1, 8, -3, 10};

for (int x : arr) {
    if (x < 0) {
        continue;  // 跳过负数
    }
    std::cout << x << " ";
}
// 输出:5 8 10

2.5 跳过无效输入 #

cpp
std::vector<int> data = {1, 0, 2, 0, 3, 0, 4};

for (int x : data) {
    if (x == 0) {
        continue;  // 跳过0
    }
    std::cout << 100 / x << " ";
}
// 输出:100 50 33 25

2.6 continue vs if-else #

cpp
// 使用continue
for (int i = 0; i < 10; i++) {
    if (condition) {
        continue;
    }
    // 处理代码
}

// 等价的if-else
for (int i = 0; i < 10; i++) {
    if (!condition) {
        // 处理代码
    }
}

三、goto语句 #

3.1 基本语法 #

cpp
goto label;
// ...
label:
    // 语句

3.2 基本使用 #

cpp
int i = 0;

start:
std::cout << i << " ";
i++;

if (i < 5) {
    goto start;
}
// 输出:0 1 2 3 4

3.3 跳出多层循环 #

cpp
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 5; j++) {
        if (i == 1 && j == 2) {
            goto found;  // 跳出所有循环
        }
        std::cout << i << "," << j << " ";
    }
    std::cout << std::endl;
}
goto end;

found:
std::cout << "\n找到了!" << std::endl;

end:
// 继续执行

3.4 错误处理 #

cpp
void processData() {
    // 分配资源
    int* buffer1 = new int[100];
    int* buffer2 = nullptr;
    
    if (!buffer1) goto error1;
    
    buffer2 = new int[100];
    if (!buffer2) goto error2;
    
    // 处理数据
    // ...
    
    // 正常退出
    delete[] buffer2;
    delete[] buffer1;
    return;
    
error2:
    delete[] buffer1;
error1:
    std::cout << "内存分配失败" << std::endl;
}

3.5 goto的限制 #

cpp
// 不能跳过变量初始化
goto label;  // 错误!
int x = 10;  // 跳过了初始化
label:
    std::cout << x << std::endl;

// 正确:在块中声明
goto label;
{
    int x = 10;
}
label:
    // ...

3.6 为什么避免使用goto #

  1. 破坏程序结构
  2. 难以理解和维护
  3. 容易产生错误
  4. 有更好的替代方案
cpp
// 不推荐:使用goto
int i = 0;
loop:
if (i < 10) {
    std::cout << i << " ";
    i++;
    goto loop;
}

// 推荐:使用循环
for (int i = 0; i < 10; i++) {
    std::cout << i << " ";
}

四、return语句 #

4.1 在循环中使用return #

cpp
// 查找元素
int findIndex(const std::vector<int>& vec, int target) {
    for (int i = 0; i < vec.size(); i++) {
        if (vec[i] == target) {
            return i;  // 找到后立即返回
        }
    }
    return -1;  // 未找到
}

4.2 return vs break #

cpp
// 使用break
void process(const std::vector<int>& vec) {
    bool found = false;
    for (int x : vec) {
        if (x == 0) {
            found = true;
            break;
        }
    }
    // 继续执行其他代码
}

// 使用return
void process(const std::vector<int>& vec) {
    for (int x : vec) {
        if (x == 0) {
            return;  // 直接退出函数
        }
    }
    // 如果没找到0,继续执行
}

五、实际应用 #

5.1 搜索 #

cpp
// 线性搜索
int linearSearch(const int arr[], int size, int target) {
    for (int i = 0; i < size; i++) {
        if (arr[i] == target) {
            return i;  // 找到,返回索引
        }
    }
    return -1;  // 未找到
}

5.2 数据验证 #

cpp
bool validateInput(const std::string& input) {
    for (char c : input) {
        if (!std::isdigit(c)) {
            return false;  // 发现非数字字符
        }
    }
    return true;  // 全部是数字
}

5.3 菜单系统 #

cpp
void menuSystem() {
    while (true) {
        displayMenu();
        int choice;
        std::cin >> choice;
        
        switch (choice) {
            case 1:
                handleNew();
                break;
            case 2:
                handleOpen();
                break;
            case 3:
                return;  // 退出菜单系统
            default:
                std::cout << "无效选择" << std::endl;
        }
    }
}

5.4 文件处理 #

cpp
void processFile(const std::string& filename) {
    std::ifstream file(filename);
    if (!file.is_open()) {
        std::cout << "无法打开文件" << std::endl;
        return;
    }
    
    std::string line;
    while (std::getline(file, line)) {
        if (line.empty()) {
            continue;  // 跳过空行
        }
        if (line[0] == '#') {
            continue;  // 跳过注释
        }
        // 处理有效行
        processLine(line);
    }
}

六、最佳实践 #

6.1 优先使用结构化控制流 #

cpp
// 不推荐:使用goto
int i = 0;
start:
if (i < 10) {
    process(i);
    i++;
    goto start;
}

// 推荐:使用循环
for (int i = 0; i < 10; i++) {
    process(i);
}

6.2 使用标志代替多层break #

cpp
// 不推荐:使用goto跳出多层
for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
        if (condition) goto exit;
    }
}
exit:

// 推荐:使用标志
bool shouldExit = false;
for (int i = 0; i < n && !shouldExit; i++) {
    for (int j = 0; j < m && !shouldExit; j++) {
        if (condition) {
            shouldExit = true;
        }
    }
}

6.3 使用函数封装复杂逻辑 #

cpp
// 不推荐:复杂的嵌套循环
for (...) {
    for (...) {
        if (...) {
            if (...) {
                // 深层嵌套
            }
        }
    }
}

// 推荐:提取函数
bool processInner(int j) {
    if (...) {
        return true;  // 相当于break
    }
    return false;
}

for (int i = 0; i < n; i++) {
    if (processInner(i)) {
        break;
    }
}

6.4 合理使用continue #

cpp
// 使用continue减少嵌套
for (int x : data) {
    if (x < 0) continue;
    if (x > 100) continue;
    if (x % 2 == 0) continue;
    
    // 处理有效数据
}

// 等价于
for (int x : data) {
    if (x >= 0 && x <= 100 && x % 2 != 0) {
        // 处理有效数据
    }
}

七、总结 #

控制语句对比 #

语句 作用 使用场景
break 跳出循环/switch 找到目标、提前退出
continue 跳过当前迭代 过滤数据
goto 无条件跳转 尽量避免
return 退出函数 找到结果、错误退出

使用建议 #

  1. break:合理使用,跳出循环
  2. continue:简化条件判断
  3. goto:尽量避免使用
  4. return:提前返回,简化逻辑

下一步,让我们学习数组!

最后更新:2026-03-26