[FrontPage] [TitleIndex] [WordIndex

Note: You are looking at a static copy of the former PineWiki site, used for class notes by James Aspnes from 2003 to 2012. Many mathematical formulas are broken, and there are likely to be other bugs as well. These will most likely not be fixed. You may be able to find more up-to-date versions of some of these notes at http://www.cs.yale.edu/homes/aspnes/#classes.

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 KernighanRitchie 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 that > 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) & (unary) ++ -- (type) sizeof

unary operators (associate right-to-left)

* (binary) / %

multiplication and division

+ (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 operators (associate right-to-left)

,

comma operator


CategoryProgrammingNotes


2014-06-17 11:57