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 @ 2022-04-08 08:30  荒年、  阅读(82)  评论(0编辑  收藏  举报