Associativity -- what is it?

Larry Jones scjones at sdrc.UUCP
Sun Feb 21 05:52:00 AEST 1988


In article <226 at mccc.UUCP>, pjh at mccc.UUCP (Peter J. Holsberg) writes:
> 
> I find that associativity is a *very* difficult thing for me to explain,
> undoubtedly because I don't understand it!  Would someone come to my
> rescue?  Here's an example (assume that everything's been declared
> correctly):
> 
> 	x = 3 * i ++;
> 
> Book says that ++ has a higher precedence than *, and that ++
> associates from R->L.  That makes me think that ++ should be applied
> first, but I know it isn't.  But ????

But ++ IS applied first!  The key point here is that the RESULT of postfix
++ is the value BEFORE incrementation, not that postfix ++ is somehow deferred
until later.

It seems that you are confusing precedence and associativity.  Precedence is
used to specify the priority of DIFFERENT operators -- since multiplication
has higher precedence that addition the expression A * B + C is interpreted
as (A * B) + C.  Associativity is used to specify the priority of operators
with the SAME PRECEDENCE -- since subtraction associates left to right the
expression A - B - C is interpreted as (A - B) - C rather than A - (B - C).

> Also, what does K&R say about these:
> 	--- a;

K&R says that tokens are always the longest string which could be a vaild
token so this is interpreted as --(-a) which is invalid since -- can only
be applied to an lvalue (which -a is not).  This has nothing to do with
precedence or associativity - the innermost operator MUST be evaluated
first, since the outer operator has no operand until it is.

> 	- -- a;

Interpreted as -(--a).  Again this has nothing to do with precedence or
associativity.

> 	-- - a;

Same as your first example.

----
Larry Jones                         UUCP: uunet!sdrc!scjones
SDRC                                MAIL: 2000 Eastman Dr., Milford, OH  45150
                                    AT&T: (513) 576-2070
"When all else fails, read the directions."



More information about the Comp.lang.c mailing list