Videos
As far as the "Real World" is concerned, it's probably fair to say:
- enough programmers know that multiplication/division take precedence over addition/subtraction, as is mathematically the convention
- hardly any programmers can remember any of the other rules of precedence
So, apart from the specific case of */ vs +-, I'd really just use brackets to explicitly define the precedence intended.
Another related source of bugs is how rounding errors accumulate. Not an operator precedence order issue per se, but a source of surprise when you get a different result after rearranging operands in an arithmetically-equivalent way. Here's a sun.com version of David Goldberg's What Every Computer Scientist Should Know About Floating-Point Arithmetic.
Yes, ++ has higher precedence than =. But you need to think of the ++ post-increment operator as 2 operations -- increment the variable and yield the old value -- that happen before the operator with lower precedence, =.
Here is what happens:
- Post-increment Operator
++: Incrementa. - Post-increment Operator
++: Yield the old value ofa. - Operator
=: Assign the old value ofatob.
It's equivalent to this code.
int resultOfPostIncrement = a;
a = a + 1;
b = resultOfPostIncrement;
As opposed to what many people seem to think, b is NOT assigned before incrementing a when we write int b = a++;. It is assigned the former value of a, but later in the timeline than the actual increment of a.
Therefore, it does not contradict what precedence tells you.
To convince you, here is a little example that convinced me:
int a = 1;
int b = a++ + a++;
At the end, b equals 3, not 2, and a is also 3. What happens because of precedence is:
- the left
a++is evaluated first, incrementinga, but still evaluated to the former value 1 by definition of the operator - the right
a++is evaluated, reading the new value 2 (proving that the first increment already happened), incrementing it to 3, but still evaluating to 2 - the sum is calculated
1 + 2, and assigned tob
This is because you should see a++ as both an instruction and an expression.
- the instruction increments
a - the expression evaluates to the former value of
a
It's the same kind of things as in b = a, which also is an instruction and an expression:
- the instruction assigns the value of
atob - the expression evaluates to the assigned value