Using the post-increment in function arguments

c++

Solution

The C++ standard states (A note in section 1.9.16):

Value computations and side effects associated with the different argument expressions are unsequenced.

In other words, it's undefined and/or compiler-dependent which order the arguments are evaluated in before their value is passed into the function. So on some compilers (which evaluate the left argument first) that code would output `10, 10` and on others (which evaluate the right argument first) it will output `11, 10`. In general you should never rely on undefined behaviour.

To help you understand this, imagine that each argument expression is evaluated before the function is called like so (not that this is exactly how it actually works, it's just an easy way to think of it that will help you understand the sequencing):

int arg1 = x;       // This line
int arg2 = x++;     // And this line can be swapped.
print(arg1, arg2);

The C++ Standard says that the two argument expression are unsequenced. So, if we write out the argument expressions on separate lines like this, their order should not be significant, because the standard says they can be evaluated in any order. Some compilers might evaluate them in the order above, others might swap them:

int arg2 = x++;     // And this line can be swapped.
int arg1 = x;       // This line
print(arg1, arg2);

That makes it pretty obvious how `arg2` can hold the value `10`, while `arg1` holds the value `11`.

You should always avoid this undefined behaviour in your code.

Problem

When I run this code, the output is 11, 10. Why on earth would that be? Can someone give me an explanation of this that will hopefully enlighten me? Thanks ``` #include <iostream> using namespace std; void print(int x, int y) { cout << x << endl; cout << y << endl; } int main() { int x = 10; print(x, x++); } ```

Original source