Re: Associativity of ++ and --




Chad wrote:
The following question stems from p.132 in the book "The C Programming
Language", second edition by K & R.

The have

struct {
int len;
char *str;
} *p;

The question is how come parentheses are need when you go like:
(++p)->len;

but you don't need them when you go:
p++->len;

The above two cases are different. e.g.:

int i = 10, j = 10;
printf("%d, %d\n", ++i + 1, j++ + 1);

The only thing I can think of would be that in the former, the prefix
operator associates right to left,
whereas in the former, the postfix operator associates left to right.
I'm I close?

In your first sample without the parentheses, the variable p is
operated by two operators: ++ and -> on its left and right sides. These
two operators are not in the same precedence, the problem does not go
to the associativity. (++p)->len; and ++p->len; are different.

In the case of p++->len;, the variable p has only one immediate
operator, no need to use a pair of parentheses on it.

.



Relevant Pages