使用 goto 语句强制执行至少一次 for 循环迭代的有效性

Validity of forcing at least one iteration of for loop with goto statement

免责声明:我知道它晦涩难懂,我不会那样编程。我知道首选 do-while 声明,而不是那个,问题更多是关于特定语言结构的有效性。


goto 是否总是应该省略 for 循环的 条件表达式 ?根据我的观察,它跳过了第一个(即初始化)和第二个表达式。这会一直以这种方式发生,还是这种行为纯粹依赖于编译器?

#include <stdio.h>

int main(void)
{
    int m = 5;

    goto BODY;
    for (m = 0; m < 5; m++)
        BODY: puts("Message"); // prints "Message" once

    printf("m = %d\n", m); // prints m = 6

    return 0;
}

您应该使用 do/while 循环,例如,如果您有以下 for 循环:

for(A ; B ; C)
{
     D;
}

您应该使用以下 do/while 循环:

A;
do
{
     D;
     C;
}while(B);

这将强制进行第一次迭代。

编辑

查看chux的评论:如果D;包含continue,这种方式不行,你需要另一种方式

编辑二

由于问题已被编辑,此答案不再是问题的直接答案,但我不会将其删除,因为它可能会对某人有所帮助...

C 编程中的 goto 语句提供从 'goto' 到同一函数中标记语句的无条件 跳转。

请注意此处的无条件术语。

所以是的,它应该省略 for 循环的条件表达式。

是的,您跳过了 m = 0m < 5,这是应该的。

for (A; B; C)
    D;

等同于

{
    A;
  loop:
    if (B)
    {
        D;
        C;
        goto loop;
    }
}

无法将控制转移到 AB 之间的点。

你的循环的语义完全像这样"pure goto"版本:

int m = 5;
goto BODY;
m = 0;
loop:
if (m < 5) 
{
  BODY: puts("Message"); // prints "Message" once
   m++;
   goto loop;
}
printf("m = %d\n", m); // prints m = 6

代码中的 goto 语句导致无条件跳转到 for loop.When 中的语句执行该语句,程序的流程应该是依赖的在 loop.So 中的条件表达式上,是的,循环内的初始化被跳过。

这在 c 中是完全合法的。只要不跳过自动变量的任何声明或初始化,跳入 for 循环就没有错。

在你的例子中,m 递增一次,并且循环由于满足停止条件而终止。

Does goto is always supposed to omit conditional expression of the for loop?

是的。 goto 跳转始终是无条件跳转,执行将从那里的 label 开始。

来自 C11 草案,§ 6.8.6.1 goto 语句

A goto statement causes an unconditional jump to the statement prefixed by the named label in the enclosing function.

唯一的例外是:

The identifier in a goto statement shall name a label located somewhere in the enclosing function. A goto statement shall not jump from outside the scope of an identifier having a variably modified type to inside the scope of that identifier.