I have to pieces of code:
int m = 4;
int result = 3 * (++m);
and
int m = 4;
int result = 3 * (m++);
After the execution m is 5 and result is 15 in the first case, but in the second case, m is also 5 but result is 12. Why is this the case? Shouldn’t it be at least the same behaviour?
I’m specifically talking about the rules of precedence. I always thought that these rules state that parantheses have a higher precedence than unary operators. So why isn’t the expression in the parantheses evaluated first?
No – because in the first case the result is 3 multiplied by “the value of
mafter it’s incremented” whereas in the second case the result is 3 multiplied by “the initial value ofmbefore it’s incremented”.This is the normal difference between pre-increment (“increment, and the value of the expression is the value after the increment”) and post-increment (“remember the original value, then increment; the value of the expression is the original one”).