-
precedence problem
I have seen a code like this:
Code:
#include <stdio.h>
int data[2]={100,300};
int moredata[2]={200,400};
int main(void)
{
int *p1,*p2,*p3;
p1=p2=data;
p3=moredata;
printf("*p1++=%d, *++p2=%d, (*p3)++=%d\n",*p1++,*++p2,(*p3)++);
return 0;
}
and what I get is *p1++==100, *++p2=300, (*p3)++=200
from what I know, ++(postfix) has higher precedence than *, why I do not get *p1++=300? and the associativity of ++(postfix) is left to right, for * is right to left, so how can I determine the associativity here? does (*p3)++ mean adding 1 to the value p3 is pointing to? why i did not get (*p3)++=201?
thanks for help!
-
*p1++
works as
Code:
int temp = *p1;
p1++;
print temp;
*++p2
works as
Code:
++p2;
int temp = *p2;
print temp;
(*p3)++
warks as
Code:
int temp = *p3;
moredata[0] ++;
print temp;
so the precedence of the operators determines what is incremented - pointer or value it points.
The postfix and prefix operator determain what value is returned by the operator - before change or after
-
>from what I know, ++(postfix) has higher precedence than *, why I do not get *p1++=300?
Since that is the postincrement operator, it performs the increment on the address AFTER the expression has been evaluated. The higher precedence just means that ++ will bind to p1, and not *p1.
In short, the value of the expression is the value of the operand, which is p1, which is dereferenced to produce 100.
> and the associativity of ++(postfix) is left to right, for * is right to left,
>so how can I determine the associativity here?
Here, * applies to p1 (right to left, p1 is on the right). ++(postincrement) also applies to p1, both because of left to right associativity and having a higher precedence than *.
>does (*p3)++ mean adding 1 to the value p3 is pointing to?
Yes, but since it's postfix, the increment occurs after the value is noted.
>why i did not get (*p3)++=201?
See above.
The changes in values can be seen if you add the following code at the end:
Code:
printf("*p1=%d, *p2=%d, (*p3)=%d\n",*p1,*p2,(*p3));
which produces:
Code:
*p1=300, *p2=300, (*p3)=201
-
i am more clear now, thanks guys!