As per the order of precedence of operators, () is evaluated before unary operators like ++ or --. But let us consider the following code:-
int x = 1;
x = 2 + (x++);
If x++ is executed first, the value of x should have been updated to 2, and hence the value of x should have been 4. However, on executing the code, the value of x is 3. Does this mean that the expression was evaluated without considering the () around x++, or am I missing something?
Let me try to explain this.
If you enclose the (x++). It is still evaluated, but its value is used before the increment (++) operation.
The order of your code goes like this:
(x++) is evaluated first. At this point x is still 1 and (x++) returns the original value of x (1) AND THEN increments x to 2.
After the x++ in parentheses is evaluated, the expression becomes x = 2 + 1, as the:
Post-increment operator x++ returns the current value of x and then increments x. Therefore, in the expression x++ returns the current value of x, (which is 1) and then increments x to 2.
So at the end of this step the expression x = 2 + 1 is 3.
At the end the result of the addition (3) is assigned to x. So the x is now 3.
For your code to return 4, you should use "++x" (pre-increment operator) This operator increments x first then returns the updated value of x. if you use the ++x in an expression, x is incremented before its value is used.
Hopefully I explained it well. :D