How to analyse the precedence in following situation .
for (i=0; i<20; i++)
{
*array_p++ = i*i;
printf("%d\n",*arr++);
}
how is following code different from above.
for (int i=0; i<20; i++)
{
*arr = i*i;
printf("%d\n",*arr);
arr++;
printf("%d\n",(int )arr);
}
I am expecting same output but outputs are different for *arr value
Postfix operators have higher precedence than unary operators, so *x++ is parsed as *(x++); the result of the expression x++ (which is x) is dereferenced.
In the case of *++x, both * and ++ are unary operators and thus have the same precedence, so the operators are applied left-to-right, or *(++x); the result of the expression ++x (which is x + sizeof *x) is dereferenced.
Citing Wikipedia, postfix ++ binds before unary *. This means that you have *(arr++). For example, in the expression *arr++ = 5, *arr is assigned to 5, then arr is incremented.
In the K&R, this trick is used to write a concise version of memcpy. It's something like:
while (--size)
*dest++ = *src++;
I'll post the correct example after I get home tonight.
Edit: Apparently, only postfix ++ has higher precedence. Wikipedia says prefix ++ has equal precedence.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With