原文: https://www.programiz.com/c-programming/c-goto-statement
在本教程中,您将学习在 C 编程中创建goto语句。 此外,您还将学习何时使用goto语句以及何时不使用它。
goto语句允许我们将程序的控制权转移到指定的标签。
goto语句的语法
goto label;... .. ...... .. ...label:statement;
label是一个标识符。 遇到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 numberif (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: 32\. Enter a number: 4.33\. Enter a number: 9.34\. Enter a number: -2.9Sum = 16.60Average = 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可以做任何事情的事实正是我们不使用它的原因”。
