在 C++ 编程中,goto 语句通过将控制转移到程序的其他部分来改变程序的正常执行顺序。
goto 语句的语法
goto label; ... .. ... ... .. ... ... .. ... label: statement; ... .. ...
在上面的语法中,label 是一个 标识符。当遇到 goto label;
时,程序控制会跳转到 label:
并执行其下方的代码。

示例:goto 语句
// This program calculates the average of numbers entered by the user.
// If the user enters a negative number, it ignores the number and
// calculates the average number entered before it.
# include <iostream>
using namespace std;
int main()
{
float num, average, sum = 0.0;
int i, n;
cout << "Maximum number of inputs: ";
cin >> n;
for(i = 1; i <= n; ++i)
{
cout << "Enter n" << i << ": ";
cin >> num;
if(num < 0.0)
{
// Control of the program move to jump:
goto jump;
}
sum += num;
}
jump:
average = sum / (i - 1);
cout << "\nAverage = " << average;
return 0;
}
输出
Maximum number of inputs: 10 Enter n1: 2.3 Enter n2: 5.6 Enter n3: -5.6 Average = 3.95
您可以在不使用 goto
语句的情况下编写任何 C++ 程序,并且通常不使用它们被认为是明智的做法。
避免 goto 语句的原因
goto 语句赋予了跳转到程序任何部分的能力,但这会使程序的逻辑变得复杂且混乱。
在现代编程中,goto 语句被认为是一种有害的结构,是一种糟糕的编程实践。
在大多数 C++ 程序中,goto 语句可以用 break
和 continue
语句的用法来替代。