Precedence and associativity of prefix and postfix in c

耗尽温柔 提交于 2019-12-19 10:08:16

问题


int main()
{
  char arr[]  = "geeksforgeeks";
  char *ptr  = arr;

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

  getchar();
  return 0;
}

The statement inside while loop ++ptr++ behaves in a way that I don't understand. The post increment should have been evaluated first because of its high priority and the first output value should have been f(incrementing e). But that does not happen. To understand i changed the statement to ++*(ptr++), so it may give the output what i expect(ffltgpshfflt is the output i expected;but actual output hffltgpshfflt). But still the output does not change. () operator has higher precedence than the pre-increment. But why does not the output change?


回答1:


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.



来源:https://stackoverflow.com/questions/27276159/precedence-and-associativity-of-prefix-and-postfix-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!