本文介绍了后增量运算符的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/6457130/$p$p-post-increment-operator-behavior-in-c-c-java-c-sharp\">$p$p &安培;在C,C ++,Java和与放大器后增量运算符的行为; C#

下面是一个测试用例:


void foo(int i, int j)
{
   printf("%d %d", i, j);
}
...
test = 0;
foo(test++, test);

我希望得到一个0 1的输出,但我得到0
是什么给了?

I would expect to get a "0 1" output, but I get "0 0"What gives??

推荐答案

这是不确定的行为的一个例子。该标准确实的不可以发言权应进行评估,按什么顺序参数。这是一个编译器实现决策。编译器是免费的参数评估,以任意顺序的功能。

This is an example of unspecified behavior. The standard does not say what order arguments should be evaluated in. This is a compiler implementation decision. The compiler is free to evaluate the arguments to the function in any order.

在这种情况下,它看起来像实际处理的参数从右向左而不是预期的左到右。

In this case, it looks like actually processes the arguments right to left instead of the expected left to right.

在一般情况下,在参数做的副作用是不好的编程习惯。

In general, doing side-effects in arguments is bad programming practice.

而不是美孚(++测试,测试); 你应该写的美孚(测试,测试+ 1);测试++;

这将是语义上等同于你正在试图完成。

It would be semantically equivalent to what you are trying to accomplish.

编辑:
正如安东尼正确地指出,这是不确定的读取和修改单个变量没有插入顺序点。因此,在这种情况下,该行为确实未定义。所以编译器是免费的C它想产生任何$ C $。

As Anthony correctly points out, it is undefined to both read and modify a single variable without an intervening sequence point. So in this case, the behavior is indeed undefined. So the compiler is free to generate whatever code it wants.

这篇关于后增量运算符的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-18 04:04
查看更多