When more than one
operator appears in an expression the order of evaluation depends on
the rules of precedence. A complete explanation of precedence can get
complicated, but just to get you started:
Multiplication and division happen before addition and subtraction. So
(remember that in integer division
If the operators have the same precedence they are evaluated from left
to right. So in the expression
, the multiplication happens first, yielding
, which in turn yields
. If the operations had gone from right to left, the result would be
, which is wrong.
Any time you want to override the rules of precedence (or you are not
sure what they are) you can use parentheses. Expressions in parentheses
are evaluated first, so
2 * (3-1)
. You can also use parentheses to make an expression easier to read, as
(iMinute * 100) / 60
, even though it doesn’t change the result.
understanding (usually accidental) of operator precedence is another
major cause of logic errors in a program. If there is a chance of
misunderstanding, it is a good idea to use parentheses.