亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> C语言

C goto 语句

C goto 语句

在本教程中,您将学习在 C 编程中创建 goto 语句。此外,您还将了解何时使用 goto 语句以及何时不使用它。

goto 语句允许我们将程序的控制权转移到指定的 label .


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的使用 声明可能会导致代码错误且难以遵循。例如,

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' 可以做任何事情,这正是我们不使用它的原因。”


C语言

  1. 蜂鸣器
  2. C# if, if...else, if...else if 和嵌套 if 语句
  3. C# switch 语句
  4. C# 中断语句
  5. C# continue 语句
  6. C++ if, if...else 和嵌套 if...else
  7. C++ 中断语句
  8. C++ switch..case 语句
  9. Python pass 语句
  10. C - 基本语法
  11. Python - 数字
  12. 什么是部件号?