goto语句

goto语句

#include <iostream>
#include <Windows.h>
#include <string>

using namespace std;

int main()
{
    string ret;

    for (int i = 0; i < 5; i++)
    {
        cout << "开始第" << i + 1 << "次相亲" << endl;
        cout << "你喜欢打王者吗?";
        cin >> ret;

        if (ret != "yes")
        {
            cout << "下次再见" << endl;
            continue;
        }

        cout << "我中意你,你中意我吗?";
        cin >> ret;
        if (ret == "yes")
        {
            goto happy;
        }
    }

    system("pause");
    return 0;

happy:
    cout << "开启浪漫之旅" << endl;
    system("pause");
    return 0;
}

image

goto语句执行效率高,但是破坏了程序的结构性,不具有可读性

这里可以封装成一个happy函数代替goto,或者也可以设置一个标志位flag

// 封装happy函数
#include <iostream>
#include <Windows.h>
#include <string>

using namespace std;

void happy()
{
    cout << "开启浪漫之旅" << endl;
}

int main()
{
    string ret;

    for (int i = 0; i < 5; i++)
    {
        cout << "开始第" << i + 1 << "次相亲" << endl;
        cout << "你喜欢打王者吗?";
        cin >> ret;

        if (ret != "yes")
        {
            cout << "下次再见" << endl;
            continue;
        }

        cout << "我中意你,你中意我吗?";
        cin >> ret;
        if (ret == "yes")
        {
            happy();
        }
    }

    system("pause");
    return 0;
}
// 设置flag标志
#include <iostream>
#include <Windows.h>
#include <string>

using namespace std;

int main()
{
    string ret;
    int flag = 0;

    for (int i = 0; i < 5; i++)
    {
        cout << "开始第" << i + 1 << "次相亲" << endl;
        cout << "你喜欢打王者吗?";
        cin >> ret;

        if (ret != "yes")
        {
            cout << "下次再见" << endl;
            continue;
        }

        cout << "我中意你,你中意我吗?";
        cin >> ret;
        if (ret == "yes")
        {
            flag = 1;
            break;
        }
    }

    if (flag)
    {
        cout << "开启浪漫之旅" << endl;
    }

    system("pause");
    return 0;
}

注意:goto只能在一个函数范围内跳转,不能跨函数跳转

结束多层循环时,可以使用goto语句。

在底层开发中,因为调用函数的话会产生开销,纯粹为了追求效率,可以用goto。

posted @   荒年、  阅读(100)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示