Search code examples
c++cpost-increment

Post increment operator behavior


Possible Duplicate:
Pre & post increment operator behavior in C, C++, Java, & C#

Here is a test case:


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

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


Solution

  • 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.

    Instead of foo(test++, test); you should write foo(test, test+1); test++;

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

    Edit: 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.