关于“goto”的问题在C中
我正在尝试理解 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这取决于 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 areturn
statement, or anothergoto
statement.在第二个版本中,即使
condition
为 false,a=1 最终也会被执行,仅仅是因为控制流最终达到done:
循环条件不再满足后。In the second version,
a=1
is eventually executed even thoughcondition
was false, simply because the control flow eventually reachesdone:
after the loop condition is no longer satisfied.