问题
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