Skip to content

C Language priorities precedence

An answer to this question on Stack Overflow.

Question

Recently I came across this program x=3*4%5/2 In an arithmetic expression, the order of precedecne will be multiplication,division and modulus. If we evaluate the expression, answer should be 0 but the answer is 1. Please explain

Answer

  1. Look up the C operator precedence table here.

  2. Note that * / % all have the same precedence and left-to-right associativity.

  3. Evaluate from left to right: 3*4%5/2 = (((3*4)%5)/2) = 1

Personally, I have a rule that if I have any uncertainty about precedence, I use parentheses to group. Relying on operator precedence is unwise: it can very between languages and styles of mathematics. A good programmer/mathematician tries to ensure that their code will evaluate as intended and also acts to clearly communicate this intention to others: parentheses eliminate ambiguity.