c - 在 C 语言中,为什么在 goto 标签后需要一个语句?

标签 c gcc

我正在编写一些 C 代码,在我的代码中有两个嵌套循环。在特定情况下,我想break 跳出内部循环并continue 外部循环。我尝试在外部循环代码的末尾使用标签来实现此目的,并且在条件下 goto 该标签。但是 gcc 给出了一个错误,我不能在复合语句的末尾添加标签。为什么不呢?

注意 1:这不是 switch 语句并且that 问题已得到回答 elsewhere .

注意 2:这不是关于样式的问题,也不是关于我是否应该使用 goto 语句或条件变量的问题。

编辑:人们要求举个例子,我可以举一个简单的例子来检查一个数组是否是另一个数组的子数组

    int superArray[SUPER_SIZE] = {...}, subArray[SUB_SIZE] = {...};
    int superIndex, subIndex;

    for (superIndex=0; superIndex<SUPER_SIZE-SUB_SIZE; superIndex+=1)
    {
      for (subIndex=0; subIndex<SUB_SIZE; subIndex+=1)
        if (superArray[superIndex+subIndex] != subArray[subIndex])
          goto break_then_continue;

      // code that executes if subArray is a sub array

      break_then_continue:
    }

最佳答案

在标准中明确指出标签属于语句,因此标签后的简单分号 (;) 可以避免您遇到的问题,因为这算作语句。

6.8.3/6 中甚至有一个使用“empty1 语句的示例。

EXAMPLE 3 A null statement may also be used to carry a label just before the closing } of a compound statement

while (loop1) {
  /* ... */

  while (loop2) {
    /* ... */

    if (want_out)
      goto end_loop1;

    /* ... */
  }

  /* ... */

  end_loop1: ;
}

1 在标准中,这称为 null 语句


6.8.1 Labeled statements

Syntax
  1 labeled-statement:
      identifier : statement
      case constant-expression : statement
      default : statement

请注意,statement 在上面的引用中不是可选的。


关于c - 在 C 语言中,为什么在 goto 标签后需要一个语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9730893/

相关文章:

c - 错误的指令 - C 代码中的内联汇编语言

C While 循环未正确退出

c++ - 模板化转换运算符的重载解析

c - 将数组中的所有值设置为零时出错

计算和打印矩阵对角线的总和

debugging - 那里有任何 flex ("Fast LEXical analyzer") 调试器吗?

c - 如何编译GCC交叉编译器?

r - Conda 构建 R 包在 MacOS Mojave 上的 C 编译器问题上失败

c - 为什么 5/7 打印 0?

c - 如何将字符串数组传递给该程序中的函数?