The increment operator with parentheses
Look at this:
Code:
x = 10
y = 2
z = x++ - (x * y)
What I first did was do what was in parentheses first (cuz that's what we're taught), since parentheses have higher precedence than the ++ operator. So first I multiplied
(10 * 2) to get 20. Then I plugged 10 in for x and thought it would evaluate to
z = 10 - 20 which would result in -10 (final value of x would be 11 after this statement executed.)
But I got it wrong. I guess the proper way to handle this is first increment x from 10 to 11. Then plug the new value 11 in where x is in the parentheses so you now have
z = 10 - (11 * 2) which results in -12.
I don't quite follow. Why doesn't the compiler first evaluate what is in parentheses? Since parentheses have a higher order of precedence anyway it seems to me the compiler would first multiply 10 * 2 to get 20.