为什么这个 C 程序会给出意外的输出?
可能的重复:
C 编程:这是未定义的行为吗?
#include<stdio.h>
main()
{
int i=5;
printf("%d%d%d",i,i++,++i);
}
我的预期输出是 556。 但当我执行它时,结果是767。 如何?
Possible Duplicate:
C programming: is this undefined behavior?
#include<stdio.h>
main()
{
int i=5;
printf("%d%d%d",i,i++,++i);
}
my expected output is 556.
But when i executed it the result is 767.
how?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
就是这样。
That's how.
有趣的是,问题在于您多次使用同一个变量。如果将代码更改为:
它会按预期工作。我认为,当您使用相同的变量时,操作顺序会变得混乱。
Interestingly Enough, the problem is that you are using the same variable more than once. If you change the code to this:
It works as expected. I think, that when you use the same variable, the order of operations gets messed up.
您正在访问和更改 序列点 内的值(事实上,更改了两次),在您无法确定操作顺序的序列点。
即,当您从左到右阅读函数调用时,不能保证表达式按该顺序计算。第一个
i
可能首先被计算,产生 5。 i++ 可能首先被计算,在++i
和i
都被计算之前递增到 6。评价等。You are accessing and changing a value within a sequence point (changing it twice, infact), Within a sequence point you can't be sure about the order of operations.
i.e. while you read the function call from left to right, it isn't guaranteed that the expressions are evaluated in that order. The first
i
might be evaluated first, yielding 5. The i++ might be evaluated first, incrementing to 6 before both++i
andi
are evaluated, and so on.您无法确定增量是否按照您期望的顺序执行,因为参数内的指令是按照编译器选择的顺序执行的。
You can't be sure that the increments are executed in the order you expect, because instructions inside arguments are executed in an order chosen by your compiler.