10.C++跳转语句-break-continue-goto

break语句

作用:用于跳出选择结构或者循环结构

break使用的时机:

  • 出现在switch条件语句中,作用是终止case并跳出switch
  • 出现在循环语句中,作用是跳出当前的循环语句
  • 出现在嵌套循环中,跳出最近的内存循环语句

示例:

#include <iostream>
using namespace std;

int main()
{
    //break 的使用时机
    
    //1、出现在switch条件语句中
    cout << "请选择副本难度" << endl;
    cout << "1、简单" << endl;
    cout << "2、一般" << endl;
    cout << "3、困难" << endl;

    int select = 0;//创建变量
    cout << "请选择副本难度" << endl;
    cin >> select;//手动选择难度

    switch (select)
    {
    case 1:
        cout << "您选择的副本难度是简单" << endl;
        break;//退出switch语句
    case 2:
        cout << "您选择的副本难度是一般" << endl;
        break;
    case 3:
        cout << "您选择的副本难度是困难" << endl;
        break;
    default:
        break;
    }
    
    ///2、出现在循环语句中
    for (int i = 0; i < 10; i++)
    {
        //如果i等于5退出循环,不再打印
        if (i == 5)
        {
            break;
        }
        cout << i << endl;
    }
    
    //3、出现在嵌套循环中
    for (int i = 0; i < 10; i++)
    {
        //如果i等于5退出循环,不再打印
        for (int j = 0; j < 10; j++)
        {
            if (j == 5)
            {
                break;//退出内层循环
            }
            cout << "* " ;
        }
        cout <<  endl;
    }

    return 0;
}

continue语句

作用:在循环语句中,跳过本次循环中余下尚未执行的语句,继续执行下一次循环

示例:

#include <iostream>
using namespace std;

int main()
{
    //continue语句

    for (int i = 0; i < 100; i++)
    {
        //如果是奇数输出,偶数不输出
        if (i % 2 == 0)
        {
            continue;//可以筛选条件,执行到此就不在向下执行,执行下一次循环
            //break会退出循环,continue会继续下一次循环
        }
        cout << i << endl;
    }

    return 0;
}

注意:break会退出循环,continue会继续下一次循环

goto语句

作用:可以无条件的跳转语句

语法:goto 标记:

解释:如果标记的名称存在,执行到goto语句的时候,会跳转到标记的位置

示例:

#include <iostream>
using namespace std;

int main()
{
    //goto语句

    cout << "111111111" << endl;

    goto FLAG;

    cout << "222222222" << endl;

    FLAG:
    cout << "333333333" << endl;

    return 0;
}

建议:不常用,使用多了对代码的阅读性有影响,建议在跳转错误的时候使用goto

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。