跳到正文

个人记录

C++精妙语句——goto

monoid_me约 1 分钟
原文
文章信息与版本

文章信息

发布
2021年9月5日
收录
2025年12月12日
更新
2026年11月15日
篇幅
约 1 分钟

版本

  1. v2当前
  2. v1

goto 是 c++ 的关键字之一,语法为

goto [lable]

其中[lable] 为标签,用[name]:; 来定义

话不多说,直接上代码

C++
#include<bits/stdc++.h>
using namespace std;
int main(){
   int a=1;
   this_is_a_lable:;//定义标签
   cout<<a++<<" ";
   if(a<=4) goto this_is_a_lable;
   return 0;
}

这段代码会输出1 2 3 4

可能现在好处不明显,但巧妙的用,就能使代码明了

顺便提一下,gotogoto 也可以跳至后面,如下:

C++
#include<bits/stdc++.h>
using namespace std;
int main(){
   int a;
   cin>>a;
   if(a>4) goto _1;
   cout<<"a不大于4时,输出这段"<<endl;
   _1:;
   cout<<"无论如何,都会输出这段";
   return 0;
}
原文