C evaluates an expression based on the usual precedence of operators: multiplication and division are done before addition and subtraction. We say that multiplication and division have higher precedence than addition and subtraction. For example, the expression
5 + 3 * 4
is evaluated by first multiplying 3 by 4 (giving 12) and then adding 5 to 12, giving 17 as the value of the expression.
As usual, we can use brackets to force the evaluation of an expression in the order we want. For example,
(5 + 3) * 4
first adds 5 and 3 (giving 8), and then multiplies 8 by 4, giving 32.
When two operators which have the same precedence appear in an expression, they are evaluated from left to right, unless specified otherwise by brackets. For example,
24 / 4 * 2
is evaluated as
(24 / 4) * 2
(giving 12) and
12 - 7 + 3
is evaluated as
(12 - 7) + 3
giving 8. However,
24 / (4 * 2)
is evaluated with the multiplication done first, giving 3, and
12 - (7 + 3)
is evaluated with the addition done first, giving 2.
In C, the remainder operator % has the same precedence as multiplication (*) and division (/).
Exercise: What is printed by the following program? Verify your answer by typing and running the program. Note: use greater than and less than signs to properly enclose 'stdio.h' instead of parantheses.
#include (stdio.h)
main() {int a = 15:int b = 24;printf("%d %d\n", b - a + 7,b - (a + 7));printf("%d %d\n", b - a - 4, b - (a - 4));printf("%d %d\n", b % a / 2, b % (a / 2));printf("%d %d\n", b * a / 2, b * (a / 2));printf("%d %d\n", b / 2 * a, b / (2 * a));}
}