question regarding precedence and associativity of ++ and *

M

maadhuu

hi,
i am a bit confused as to how *i++ (i is a pointer) works.....the postfix
+ has a higher precedence than prefix ++ and i think precedence is from
left to right whereas ,prefix ++ and * have same precedence and think its
from right to left......
well, can someone plss enlighten me how this works ??
thanx.
 
R

Richard Heathfield

maadhuu said:
hi,
i am a bit confused as to how *i++ (i is a pointer) works.....the postfix
+ has a higher precedence than prefix ++ and i think precedence is from
left to right whereas ,

The precedence of + is irrelevant. The "maximum munch" principle ensures
that ++ will be recognised.
prefix ++ and * have same precedence and think its
from right to left......
well, can someone plss enlighten me how this works ??

First think about the ++. As you know, i++ has two jobs: one of those jobs
is to increase the value of i by one (or, in the case of a pointer, to
point to the next object along), and the OTHER job is to "return" i's old
value. Now we can think about the *. It is given i's OLD value to work
with, not i's new value. Thus, you would expect this code:

#include <stdio.h>

int main(void)
{
int array[] = { 0, 42 };
int *i = array;

*i++ = 6;
printf("%d\n", array[0]);
printf("%d\n", array[1]);
printf("ptr incremented? %s\n", i == &array[1] ? "Yes" : "No");
return 0;
}

to display

6
42
ptr incremented? Yes
 

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,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top