cpointersoperator-precedence

What's the difference between *p++ and *p += 1 in C?


I have just started learning about pointers in C and was using a pointer p to iterate through the elements of an array.
My goal was to increment every element by one, but after applying the increment operator, I noticed a rather confusing output. Instead of showing value + 1, it would only show odd numbers within the array.

Here's the code:

#include <stdio.h>

#define N 10

int main(void)
{
    int a[N] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, *p;
    for (p = &a[0]; p < &a[N]; p++)
    {   
        *p++;
        printf("%d ", *p);
    }
    
    return 0;
}

output:

1 3 5 7 9

I then replaced ++ with += 1, and the output was as I was first expecting:

1 2 3 4 5 6 7 8 9 10

I don't really understand what happened here, until now I thought both notations were equivalent for every use case.


Solution

  • What's the difference between *p++ and *p += 1 in C99?

    It is a matter of operator precedence:

    1. *p++:
      ++ has higher precedence over dereferencing *,
      and so it is equivalent to: *(p++).
      I.e. the pointer is incremented and then dereferenced.

    2. *p += 1:
      dereferencing * has higher precendnce over +=,
      and so it is equivalent to: (*p) += 1.
      I.e. the pointer is dereferenced, and then the result is incremented.

    If you want to have the result of (2) (*p += 1) without using +=, you can achieve it by using parenthesis, i.e.: (*p)++.
    Alternatively you can use pre-increment which does not even require parenthesis: ++*p.