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;
}
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。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现