Precedence and associativity of prefix and postfix in c

前端 未结 1 2021
逝去的感伤
逝去的感伤 2021-01-14 20:29
int main()
{
  char arr[]  = \"geeksforgeeks\";
  char *ptr  = arr;

  while(*ptr != \'\\0\')
      ++*ptr++;
  printf(\"%s %         


        
相关标签:
1条回答
  • 2021-01-14 20:54

    We have:

    ++*ptr++
    

    First, the postfix operator is applied as you said. However, as per definition of the postfix increment operator, ptr++ evaluates to ptr and increases ptr by 1. The expression does not evaluate to the increased value, but to the original value.

    So *(ptr++) evaluates to the same value as *ptr, the former just also increases ptr. Therefore, the first element in the array is modified in the first pass of the algorithm.

    The parentheses don't matter because the postfix increment already has precedence.

    If you replace this with:

    ++*++ptr
    

    you get

    gffltgpshfflt
    

    where the order of execution of operators is the same; the difference is that prefix ++ works differently than postfix ++ - it evaluates to the increased value. Note that this also messes up the null terminator, as ptr is modified before it is checked for equality to 0.

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