后缀和前缀运算符作为函数参数 - 为什么会发生这种情况?
我在执行以下一个简单的 C 程序时遇到一个非常有趣的事实:
#include<stdio.h>
int main( )
{
int k=0;
printf("%d%d%d", k++, k, ++k);
return 0;
}
在 Windows 中它显示输出为: 1 1 1
但在 linux(ubuntu) 中它显示为: 1 2 2
为什么会这样?
I came across a very interesting fact while executing the following a simple c program:
#include<stdio.h>
int main( )
{
int k=0;
printf("%d%d%d", k++, k, ++k);
return 0;
}
in windows it was showing output as: 1 1 1
but in linux(ubuntu) it was showing as: 1 2 2
why is it so?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是未定义的行为。当没有/不明确的序列点时。请参阅这篇维基百科文章:
http://en.wikipedia.org/wiki/Sequence_point
It's undefined behaviour. When there are no / ambiguous sequence points. See this wikipedia article:
http://en.wikipedia.org/wiki/Sequence_point
有两个问题。首先是
printf
调用中表达式k++
、k
和++k
的顺序未指定评估;编译器可以按照它认为合适的任何顺序自由地评估它们。其次,对象的存储值可能不会通过表达式的求值在序列点之间多次更新。k++
和++k
都尝试更新存储在k
中的值,并且这些表达式之间没有序列点,因此行为是不明确的; 任何结果都是允许的。There are two problems. First is that the order in which the expressions
k++
,k
, and++k
in theprintf
call are evaluated is not specified; the compiler is free to evaluate them in any order it sees fit. Second is that an object may not have its stored value updated more than once between sequence points by the evaluation of an expression. Bothk++
and++k
attempt to update the value stored atk
, and there is no sequence point between those expressions, so the behavior is undefined; any result is permitted.该标准没有指定计算例程参数的顺序。
编写依赖于顺序的代码是不可移植的。
The standard does not specify an ordering in which the arguments of a routine are evaluated.
Writing code that depends on the ordering is not portable.