1

I did a recursion exercise and I could not understand what is the difference between doing *p++ or *p+=1.

Both of them should add 1 to the value pointed at but for some reason *p+=1 works and *p++ doesn't.

void rec(char a[], int *p ,int i)
{
    if(a[i+1]== '\0')
        return;

    if(a[i]==a[i+1])
        *p+=1;

    rec(a, p, i+1);
}


void rec(char a[], int *p ,int i)
{
    if(a[i+1]== '\0')
        return;

    if(a[i]==a[i+1])
        *p++;

    rec(a, p, i+1);
}
underscore_d
  • 6,309
  • 3
  • 38
  • 64
gabi939
  • 107
  • 2
  • 8
  • 1
    Possible duplicate of [Post-increment on a dereferenced pointer?](https://stackoverflow.com/questions/859770/post-increment-on-a-dereferenced-pointer) – underscore_d Dec 12 '17 at 12:17

2 Answers2

1

*p += 1; means, dereference the pointer p and then increment the dereferenced value by 1. While *p++; means

*p;
p += 1; // Increment the pointer itself  

This is because ++ has higher precedence than * operator so compiler will parse it as *(p++);.

(*p)++ is equivalent to *p += 1;.

haccks
  • 104,019
  • 25
  • 176
  • 264
1

Precedence wise

++ > * > +=

Here *p+=1 is increasing the value that is pointed by p. Here the value at the memory location pointed by p is incremented. You can see the change in your code.

In the second case, *p++ it is just increasing the pointer p and then it de-references the value but you don't assign that r-value anywhere. This is not changing the actual content that there is in the memory pointed by p.

That is why in second case you don't see any change in the working variables and concluded that it doesn't work which is certainly not the case.

user2736738
  • 30,591
  • 5
  • 42
  • 56