Associativity of ++ and --

C

Chad

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 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?

Chad
 
L

lovecreatesbea...

Chad said:
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.
 
A

a.laforgia

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;

Associativity of ++ and -- is from right to left, while associativity
of -> is from left to right.
If you wrote "++p->len" that would mean "increment p->len".
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top