x = 1 i expect the answer to be 11, but it comes out to be 12.
We explain it by expecting undefined behaviour rather than any particular result. As the expression attempts to modify x multiple times without an intervening sequence point its behaviour is undefined.
This is actually undefined. C++ doesn't define explicitly the order of execution of a statement so it depends on the compiler and this syntax shouldn't be used.
The operator priority explain the ++ operator occurs first.
Therefore: ++x occurs 3 times: then x=4 and finally: 4 + 4 + 4 = 12
Hijack: this is wrong, see thread on gamedev.net for a few explanations, and correct answer below.
as of 2007 compilers documented in gamedev thread:
VC8: x==12
Borland & GCC: x==10
You've got ++x three times, so that's 4, three times four is 12. The increments of x are done first, the value that this evaluates to is found later.
As others have said, the C and C++ standards do not define the behaviour that this will produce.
But for those people who don't see why the standards would do such a thing, let's go through a "real world" example:
1 * 2 + 3 + 4 * 5
There's nothing wrong with calculating 1 * 2 + 3
before we calculate 4*5
. Just because multiplication has a higher precedence than addition doesn't mean we need to perform all multiplication in the expression before doing any addition. In fact there are many different orders you validly could perform your calculations.
Where evaluations have side effects, different evaluation orders can affect the result. If the standard does not define the behaviour, do not rely on it.
The code snippet will invoke Undefined behavior in both C/C++.Read about Sequence Point from here.
try putting in (++x)+(++x)+(--x), (++x)+(--x)+(++x) or (--x)+(++x)+(++x)