how the expression *p++ and ++*p works differently

前端 未结 2 1214
执笔经年
执笔经年 2021-01-28 01:52
#include
int main()
{
    int a[2]={10,4};
    int *k;
    int *j; 
    j=a;
    k=j; 
    printf(\"j=%d,k=%d\\n\\n\",*j,*k);
    *j++;
    ++*k;
    prin         


        
2条回答
  •  梦如初夏
    2021-01-28 02:10

    You have two things going on here:

    • The different semantics between prefix and postfix ++;

    • Different precedence of prefix and postfix operators.

    Postfix operators have higher precedence than unary (prefix) operators, so the expression *p++ is parsed as *(p++) - you're applying the * operator to the result of p++. By contrast, the prefix ++ operator and unary * have the same precedence, so the expression ++*p is parsed as ++(*p) - you're applying the ++ operator to the result of *p.

    Also remember that prefix and postfix ++ have slightly different behavior. Both increment their operand as a side effect, but the result of postfix ++ is the current value of the operand, while the result of prefix ++ is the value of the operand plus 1.

提交回复
热议问题