评估函数调用中的参数 [英] Evaluation of arguments in function calls
问题描述
问题链接 >
20. main()
{
int i = 5;
printf("%d %d%d%d%d%d",i ++,i - ,++ i, - i,i);
}
输出为45545.但我得到了45555.请澄清。
一般如何解决这些问题?
Link to the question
20. main()
{
int i=5;
printf("%d%d%d%d%d%d",i++,i--,++i,--i,i);
}
The output is given as 45545. But I am getting 45555. Please clarify.
In general how to resolve these kind of problems?
推荐答案
Link问题
20. main()
{
int i = 5;
printf("%d%d%d%d%d%d",i ++,i - ,++ i, - i,i);
}
输出为45545.但我得到45555.请澄清。
一般如何解决这类问题?
Link to the question
20. main()
{
int i=5;
printf("%d%d%d%d%d%d",i++,i--,++i,--i,i);
}
The output is given as 45545. But I am getting 45555. Please clarify.
In general how to resolve these kind of problems?
好问题。
我刚刚意识到编译你的例子是从右到左读取参数。
无论如何,我看到输出45545的逻辑:
拿5;
从右到左:
i:传递5到printf
--i:摘要1,然后打印。将4传递给printf
++ i:添加1,然后打印。将5传递给printf
i--:将5传递给printf,然后减去1。我们得到4
i ++:将4传递给printf,然后添加一个。我们得到5
不是吗?
Nice problem.
I just realized compiling your example that parameters are read from right to left.
Anyway, I see logical the output 45545:
Take 5;
From right to left:
i : passes 5 to printf
--i: Substracts 1, and then prints. passes 4 to printf
++i: Adds 1, and then prints. passes 5 to printf
i--: passes 5 to printf, and then substracts one. We get 4
i++: passes 4 to printf, and then adds one. We get 5
Isn''t it?
不是吗?
Isn''t it?
不,不是吗?根据标准修改一个可修改的左值(例如
变量''i''),在达到序列点之前不止一次导致
未定义的行为和任何东西都可以发生。
亲切的问候,
Jos
No it isn''t; according to the Standard modifying a modifiable lvalue (such as
variable ''i'') more than once before a sequence point has been reached causes
undefined behaviour and anything can happen.
kind regards,
Jos
有人知道是否报告/记录在GCC描述的行为?
Does anybody know if is it reported / documented in GCC the described behavior?
这篇关于评估函数调用中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!