Increment Operators vs. Precedence

Fred Zlotnick fred at mindcraft.com
Thu Mar 7 07:22:06 AEST 1991


In article <THOMSON.91Mar5173421 at zazen.macc.wisc.edu> thomson at zazen.macc.wisc.edu (Don Thomson) writes:
>So here I am teaching an introductory C class and have just finished
>precedence and associativity and moved on to prefix and postfix increment
>operators.  The example on the board is y = x++, and I explain that x gets
>assigned to y before x is incremented.  An astute individual in the back of
>the room raises his hand and points out that according to what I just taught
>them, the precedence is wrong, that in fact the assignment operator has a
>significantly lower precedence than ++.  So the dilemma is how to explain that
>precedence is not the issue here, that the order of operations is tied to the
>definition of prefix versus postfix increment operators.  Any ideas on how to
>word the explanation in such a way that I don't leave them forever suspicious
>about what does and what does not have to obey precedence rules?

A friend of mine who teaches at Mills College just asked me a remarkably
similar question.  The best explanation I could come up with is that
precedence does not specify order of evaluation.  It describes the default
parenthesization (if there is such a word).  Thus the precedence rule you
cited just means that "y = x++" is interpreted as "y = (x++)".  The value
of the expression (x++) is the value of x before being incremented.  (If the
precedence was reversed, it would be interpreted as "(y = x)++", which is
meaningless.)  A related example is the conditional expression
	x++ && y++ || z++
The precedence rules state that this means
	((x++) && (y++)) || (z++)
As it happens, there is an order of evaluation rule for && and ||, and it
causes strange results here: x is always incremented, y is incremented
if x was not -1, and z is incremented only if x and y were both -1.  Thus
even though ++ is the highest precedence operator in this expression, not
all ++'s get evaluated.  Note that for most C operators (anything except &&,
||, ?: and comma) there is no specified order of evaluation.

Hope this helps.
Fred Zlotnick                       |	#include <std.disclaimer>
fred at mindcraft.com                  |	#include <brilliant.quote>
...!{decwrl,ames,hpda}!mindcrf!fred |



More information about the Comp.lang.c mailing list