for 循环中未定义的行为 - 表达式分离不应该使其定义明确吗?
我知道这个话题在 SO 上已经被打败了一点,但我仍然对下面显示的情况有点困惑 - 而且很多人似乎都同意这是正确的。
我知道如果没有中间序列点,您不能多次修改/使用修改后的变量,否则它会成为未定义的行为。我认为在 for 循环中, i != 0;
, i
n;
和 i--
都是单独的表达式,在已知时间求值,并由序列点分隔(因为它们是完整表达式)。
为什么这会产生未定义的行为?
I know this topic has been beaten to death a little on SO, but I'm still a little confused about the situation shown below - and multiple people seemed to agree it was right.
I understand that you cannot modify/use a modified variable more than once without an intervening sequence point without it being undefined behavior. I thought that within a for loop though, the i != 0;
, i < n;
and i--
were all separate expressions, evaluated at known times, and separated by sequence points (as they are full expressions).
Why would this yield undefined behavior?
taken from forum: http://www.frihost.com/forums/vt-48979.html
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于帖子的原始代码,
由于有符号整数算术的工作方式,代码未定义。无法保证
i
会回绕并变为正值。使用无符号算术,代码将被定义(但行为未指定,因为unsigned int
的大小未指定)。至于与屏幕截图相对应的行,变量
i
从未初始化,因此存在未定义的行为。For the original code of the post
the code is undefined because of the way signed integer arithmetic works. There is no guarantee that
i
will ever wrap around and become positive. With unsigned arithmetic, the code becomes defined (but the behavior is unspecified, because the size of anunsigned int
is unspecified).As for the line corresponding to your screenshot, the variable
i
is never initialized, hence the undefined behavior.如果
i
是有符号整数并且i--
表达式导致i
溢出,则此代码是未定义行为。 (实际上,在 C 术语中,只有有符号整数才会溢出。)This is code is undefined behavior if
i
is a signed integer AND if thei--
expression makesi
overflows. (Actually in the C terminology only signed integers can overflow.)其他答案评论的代码与实际发布的代码不同。该代码最初是一个谜题,建议的解决方案之一是编写以下内容:
这样做的问题是它永远不会为
i
分配初始值。通常,这会进入 for 结构的第一部分,但这里已被重写为(完全没有意义的)i != 0
。 (这是毫无意义的,因为它没有副作用,并且它的值没有被使用——但是,嘿,这是一个谜题。)因此,这可以运行循环任意次数。
The other answers commented on a different code than the one actually posted. The code was originally a puzzle, and one of the proposed solutions was to write the following:
The problem with this is that it never assigns an initial value to
i
. Normally, this goes into the first part of thefor
-construct, but here is has been rewritten into (the totally pointless)i != 0
. (It is pointless as it has no side effects and it's value is not used -- but, hey, this was a puzzle.)Hence, this can run the loop an arbitrary number of times.