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++);
}
The C++ standard states (A note in section 1.9.16):
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, 10and on others (which evaluate the right argument first) it will output11, 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):
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:
That makes it pretty obvious how
arg2can hold the value10, whilearg1holds the value11.You should always avoid this undefined behaviour in your code.