C++ goto語句

C++ goto語句也稱為跳轉語句。 它用於將控制轉移到程式的其他部分。 它無條件跳轉到指定的標籤。

它可用於從深層嵌套迴圈或switch case標籤傳輸控制。

C++ Goto語句示例

下麵來看看看C++中goto語句的簡單例子。

#include <iostream>
using namespace std;
int main()
{
ineligible:
    cout<<"You are not eligible to vote!\n";
    cout<<"Enter your age:\n";
    int age;
    cin>>age;
    if (age < 18){
        goto ineligible;
    }
    else
    {
        cout<<"You are eligible to vote!";
    }
    return 0;
}

上面代碼執行結果如下 -

You are not eligible to vote!
Enter your age:
16
You are not eligible to vote!
Enter your age:
7
You are not eligible to vote!
Enter your age:
22
You are eligible to vote!

上一篇: C++ continue語句 下一篇: C++注釋