Operator precedence in c with pointers

后端 未结 5 1783
面向向阳花
面向向阳花 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: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.

提交回复
热议问题