Increment Operators vs. Precedence

Joseph Schwartz xor at aix01.aix.rpi.edu
Wed Mar 6 11:43:08 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?

I'd explain that every expression has a value, and that some operators have
side effects as well.  In your example, you confuse the issue by saying that
the assignment occurs before the increment.  That isn't strictly true.
In fact, the expression x++ has a VALUE of x, and it has the side-effect
of incrementing x after the value is determined.  The = operator also has
a side-effect: it assigns a value to y.  So here's how I'd break down your
example:
 
y = x++  is equivalent to  y = (x++)  because of precedence rules.
 
(x++)  is an expression whose value is the current value of x.  It has
the side-effect of incrementing x AFTER its value is determined.
 
y = foo  is an expression whose value is the value of y.  It has the
side-effect of assigning the value of foo to y, BEFORE the value of y
is determined.

The tricky part is explaining whether side-effects occur before or after
the value of an expression is determined.  In expressions like a = b,
a += b, a *= b, a/= b, a -= b, a %= b, a >>= b, a <<= b, ++a, and --a,
the side-effect happens before the value of a is determined.  Only in
expressions like a++ and a-- does the side-effect happen afterwards.
(Am I forgetting any other operators with side-effects?)
 
I don't think of precedence rules playing a very large part in this
explanation.  Precedence rules determine what the individual sub-
expressions are; they don't determine the order that side-effects
occur in.



More information about the Comp.lang.c mailing list