Operator precedence in C

Operator precedence in C controls the interpretation of ambiguous expressions like 2+3*4, which could in principle be parsed either as 2+(3*4) (the right way) or as (2+3)*4 (the cheap calculator way). For the most part, C parses unparenthesized expressions the right way, but if you are not sure what it will do with an expression, you can always put in parentheses to force it to do the right thing.

There is a table on page 53 of Kernighan and Ritchie that shows the precedence of all operators in C, which we reproduce below.

The interpretation of this table is that higher entries bind tighter than lower ones; so the fact that * has higher precedence that + and both have higher precedence than > means that 2+3*4 > 5 gets parsed as (2+(3*4)) > 5.

Associativity controls how an expression with multiple operators of the same precedence is interpreted. The fact that + and - associate left-to-right means that the expression 2+3-4-5 is interpreted as (((2+3)-4)-5): the leftmost operation is done first. Unary operators, ternary ?: and assignment operators are the only ones that associate right-to-left. For assignment operators, this is so x = y = 0 is interpreted as x = (y = 0) (assigning 0 to both x and y) and not (x = y) = 0 (which would give an error because (x = y) isn’t something you can assign to). For unary operators, this mostly affects expressions like *p++, which is equivalent to *(p++) (increment the pointer first then dereference it) rather than (*p)++ (increment the thing that p points to).

() [] -> . function calls and indexing
! ~ - (unary) * (unary) &(unary) ++ -- (type) sizeof unary operators (associate right-to-left)
* (binary) / % multiplication and division
+ (binary) - (binary) addition and subtraction
<< >> shifts
< <= >= > inequalities
== != equality
& (binary) bitwise AND
^ bitwise XOR
| bitwise OR
&& logical AND
|| logical OR
?: ternary if (associates right-to-left)
= += -= *= /= %= &= ^= |= <<= >>= assignment (associate right-to-left)
, comma

Licenses and Attributions


Speak Your Mind

-->