关于“goto”的问题在C中

发布于 2024-10-04 19:36:26 字数 456 浏览 0 评论 0原文

我正在尝试理解 C 代码。在某些部分有:

for ...{
    if condition{
       a=1;
       break;
    }
}

在以后的版本中更改为:

for ...{
    if condition{
       goto done;
    }
}
done: a=1;

从我的角度来看,两个版本应该给出相同的结果,但它不会发生。你知道为什么吗?

更正:修复方法是:

for ...{
    if condition{
       goto done;
    }
}

            goto notdone;
            done: 
                ok=0;
            notdone:

I am trying to understand a C code. In some part there is:

for ...{
    if condition{
       a=1;
       break;
    }
}

which in a later version is changed to:

for ...{
    if condition{
       goto done;
    }
}
done: a=1;

From my point of view, both vesions should give the same result, but it does not happen. Do you know why?

CORRECTION: The fix is:

for ...{
    if condition{
       goto done;
    }
}

            goto notdone;
            done: 
                ok=0;
            notdone:

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

过期情话 2024-10-11 19:36:26

这取决于 for 循环是否有任何其他退出条件。

  • 在第一个示例中,a=1 仅在 if 语句中的特定退出条件下发生。

  • 在第二个示例中,a=1 发生在所有退出循环的场景中。只能使用 return 语句或另一个 goto 语句来规避它。

It depends on whether the for-loop has any other exit conditions.

  • In the first example, a=1 only happens for that specific exit condition in the if-statement.

  • In the second example, a=1 happens in all scenarios that exit the loop. It can only be circumvented using a return statement, or another goto statement.

自此以后,行同陌路 2024-10-11 19:36:26

在第二个版本中,即使 condition 为 false,a=1 最终也会被执行,仅仅是因为控制流最终达到 done: 循环条件不再满足后。

In the second version, a=1 is eventually executed even though condition was false, simply because the control flow eventually reaches done: after the loop condition is no longer satisfied.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文