goto
语句允许我们将程序的控制转移到指定的标签。
goto语句的语法
goto label;
... .. ...
... .. ...
label:
statement;
标签是一个标识符。当遇到goto
语句时,程序的控制将跳转到label:
并开始执行代码。

示例:goto语句
// Program to calculate the sum and average of positive numbers
// If the user enters a negative number, the sum and average are displayed.
#include <stdio.h>
int main() {
const int maxInput = 100;
int i;
double number, average, sum = 0.0;
for (i = 1; i <= maxInput; ++i) {
printf("%d. Enter a number: ", i);
scanf("%lf", &number);
// go to jump if the user enters a negative number
if (number < 0.0) {
goto jump;
}
sum += number;
}
jump:
average = sum / (i - 1);
printf("Sum = %.2f\n", sum);
printf("Average = %.2f", average);
return 0;
}
输出
1. Enter a number: 3 2. Enter a number: 4.3 3. Enter a number: 9.3 4. Enter a number: -2.9 Sum = 16.60 Average = 5.53
避免goto的原因
goto
语句的使用可能导致代码容易出错且难以理解。例如,
one:
for (i = 0; i < number; ++i)
{
test += i;
goto two;
}
two:
if (test > 5) {
goto three;
}
... .. ...
此外,goto
语句允许您执行不好的操作,例如跳出作用域。
话虽如此,goto
有时也可能有用。例如:跳出嵌套循环。
您应该使用goto吗?
如果您认为goto
语句的使用可以简化您的程序,则可以使用它。话虽如此,goto
很少有用,您可以完全不使用goto
来创建任何C程序。
引用C++的创建者Bjarne Stroustrup的一句话:“‘goto’可以做任何事情,这正是我们不使用它的原因。”