Why is *p++ different from *p += 1?
Consider:
void foo1(char **p) { *p++; }
void foo2(char **p) { *p += 1; }
and
char *s = "abcd";
char *a = s;
foo1(&a);
printf("%s", a); //abcd
but if I use foo2()
instead of:
char *a = s;
foo2(&a);
printf("%s", a); //bcd
Can someone explain it?
Solution 1:
The key is the precedence of the +=
and the ++
operator. The ++
has a higher precedence than the +=
(in fact, assignment operators have the second lowest precedence in C), so the operation
*p++
means dereference the pointer, then increment the pointer itself by 1 (as usually, according to the rules of pointer arithmetic, it's not necessarily one byte, but rather sizeof(*p)
regarding the resulting address). On the other hand,
*p += 1
means increment the value pointed to by the pointer by one (and do nothing with the pointer itself).
Solution 2:
Precedence. The postfix ++
binds tighter than the prefix *
so it increments p
. The +=
is at the low end of the precedence list, along with the plain assignment operator, so it adds 1 to *p
.