@mazzica
int ansPre=v2 + v2++ + v2++ ;//execute line then inc so res =8 + 8 +8
This is wrong. The postfix increment operator does not perform the increment after the line is completely executed. It performs the increment where it appears in the expression, however, the result of the expression is the original value.
I reiterate my equivalence code:
int post_increment(int& i) {
int result = i; //record the value of the variable _before_ incrementing it.
i = i + 1; //increment the variable 'i' by 1.
return result; //return the value recorded before the increment.
};
The expression:
int ansPre= v2 + v2++ + v2++;
is equivalent to:
int ansPre= v2 + post_increment(v2) + post_increment(v2);
Which, actually, has undefined behaviour due to the fact that there is no rule, in the standard, to prescribe the order by which the operands of an expression are evaluated. So, the possible results are (also note that the addition is right-to-left associative):
int ansPre = 8 + (8 + 9); // (a)
int ansPre = 8 + (9 + 8); // (b)
int ansPre = 10 + (8 + 9); // (c)
int ansPre = 10 + (9 + 8); // (d)
There is no telling what your compiler might produce as a result. This is the same reason why there is no way to tell what ( i == i++ ) will give, neither could you tell what ( i == ++i ) would yield. This is undefined behaviour! That's why one should be very careful with such increment / decrement operations within compound expressions.
@triumphost: You might want to somewhat ignore what I just said, it has to do with order of evaluation of operands in an expression or function call, which is something you should understand eventually, but for now, start by understanding pre- and post-increment operators.
>> But if the ++ executes before % then should the answer be 2??
The increment executes before the %, BUT the value that the expression v1++ evaluates to is the value that v1 had BEFORE it was incremented. So, the overall result is indeed supposed to be 3.