rahul kumar
rahul kumar

Reputation: 21

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

#include<stdio.h>
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;
    printf("j=%d,k=%d",*j,*k);
    return 0;
} 

The output is:

j=10 k=10 j=4 k=11

I thought that it should have same result but this is not the case. I wished to ask what is causing this difference. I didn't got the reason behind it.

Upvotes: 0

Views: 219

Answers (2)

John Bode
John Bode

Reputation: 123458

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.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234685

You need to dig out your operator precedence table.

*p++ is evaluated as *(p++)

++*p is evaluated as ++(*p)

The second one is due to the prefix ++ having the same precedence as pointer dereference * so associativity (which is from right to left for those operators) comes into play.

For completeness' sake, *(p++) dereferences the current value of p, and p is increased by one once the statement completes. ++(*p) adds 1 to the data pointed to by p.

Upvotes: 3

Related Questions