Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator precedence in c with pointers

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

like image 925
Imposter Avatar asked Oct 27 '25 10:10

Imposter


2 Answers

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.

like image 193
John Bode Avatar answered Oct 30 '25 00:10

John Bode


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.

like image 22
Oscar Korz Avatar answered Oct 29 '25 23:10

Oscar Korz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!