What would the evaluation order of x = x++ + ++x; be?
c, c++
Solution
It is unspecified which of the arguments to `+` is evaluated first - but that doesn't even matter, because in C and C++, modifying the same object twice without an intervening sequence point is completely undefined behaviour.
Here you're modifying `x` three times without an intervening sequence point, so you're well into here be dragonnes territory ;)
The relevant part of the C99 standard is "6.5 Expressions":
2 Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.
and
3 The grouping of operators and operands is indicated by the syntax. Except as specified later (for the function-call (), &&, ||, ?:, and comma operators), the order of evaluation of subexpressions and the order in which side effects take place are both unspecified.
It's possible to write legal code that demonstrates the unspecified order of evaluation - for example:
#include <stdio.h>
int foo(void)
{
puts("foo");
return 1;
}
int bar(void)
{
puts("bar");
return 2;
}
int main()
{
int x;
x = foo() + bar();
putchar('\n');
return x;
}
(It is unspecified whether you get output of `foobar` or `barfoo`).
Problem
Possible Duplicate: Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…) In Java the evaluation order is specified to be left-to-right. Is this the case for C and C++ as well, or is it implementation dependent? I do remember that the evaluation order is unspecified for function arguments, but what about sub-expressions?