Operator precedence in c with pointers

后端 未结 5 1767
面向向阳花
面向向阳花 2020-12-30 19:13

How to analyse the precedence in following situation .

for (i=0; i<20; i++)
{
    *array_p++ = i*i;
    printf(\"%d\\n\",*arr++);
}

how

相关标签:
5条回答
  • 2020-12-30 19:16

    Operators ++ and * have the same precedence (postfix or prefix).However the associativity in such cases is from right to left. so in cases like

    *ptr++ ==>  *(ptr++) 
    *++ptr ==> *(++ptr)
    ++*ptr ==> ++(*ptr)
    

    this link should give you more information on operators precedence and their associativity.. http://www.isthe.com/chongo/tech/comp/c/c-precedence.html

    0 讨论(0)
  • 2020-12-30 19:22

    It is easy to remember which has precedence when you consider prefix increment.

    what has precedence here?

    *++array = x; // pretty obvious

    the same precedence rules go for the postfix expression so its rather easy.

    The same goes for the cast operator.

    (somestruct *)x + 1;

    first the cast is done since if it wasn't the following wouldnt make sense

    x + (int)1;

    0 讨论(0)
  • 2020-12-30 19:28

    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.

    0 讨论(0)
  • 2020-12-30 19:37

    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.

    0 讨论(0)
  • 2020-12-30 19:37

    In the first sample code snippet,

        for (i=0; i<20; i++)
            {
              *array_p++ = i*i;
               printf("%d\n",*arr++);
        }
    

    array_ptr is incremented first i.e address, and then the value computed from i*i is assigned to *array_ptr since evaluation takes in the order of right to left i.e *(array_ptr ++).

    In the second sample of code snippet,

    for (int i=0; i<20; i++)
    {
      *arr = i*i;
    printf("%d\n",*arr);
     arr++; 
    printf("%d\n",(int )arr);
    }
    

    value computed from i*i is first computed and assigned to *arr, then pointer pointing to arr is incremented.

    Hence there is difference in values among the 2 code snippets.

    0 讨论(0)
提交回复
热议问题