Sub topic 7
Precedence traps: *p++, (*p)++, and *++p
This chapter assumes you can declare and dereference pointers, you know that p + 1 moves a pointer by one element, and you know that an array name usually decays to a pointer to its first element. Combining * with ++ in one expression is a favorite GATE trap. The code is legal, but readers parse it wrongly.
The two rules that decide everything
C ranks operators in groups. Two groups matter here.
| Group | Operators | Associativity |
|---|---|---|
| Postfix (highest) | `a[i]`, `f()`, `.`, `->`, `x++`, `x--` | left to right |
| Prefix (next) | `++x`, `--x`, unary `*`, unary `&`, `sizeof`, casts | right to left |
Postfix ++ binds tighter than unary *. The prefix operators group from right to left, so *++p means *(++p) and ++*p means ++(*p).
Each increment also has a value and a side effect:
x++has the old value ofx. The increment happens as a side effect.++xhas the new value ofx.
The four forms
| Expression | Parsed as | Value of the expression | What changes |
|---|---|---|---|
| `*p++` | `*(p++)` | the element `p` pointed to before | `p` moves to the next element |
| `*++p` | `*(++p)` | the next element | `p` moves to the next element |
| `(*p)++` | `(*p)++` | the old element value | the element is incremented, `p` stays |
| `++*p` | `++(*p)` | the new element value | the element is incremented, `p` stays |
*p++ and *++p change the pointer. (*p)++ and ++*p change the data. The parentheses in (*p)++ are required. Without them the expression is *p++, and that moves the pointer.
Tracing a mixed example
This program starts with p at a[0] and applies the first two forms in turn.
#include <stdio.h>
int main(void) {
int a[3] = {1, 2, 3};
int *p = a;
int x = *p++;
int y = (*p)++;
printf("%d %d %d %d\n", x, y, a[1], (int)(p - a));
return 0;
}It prints 1 2 3 1. Trace it step by step:
*p++yieldsa[0], which is 1, soxis 1. Thenpadvances toa[1].(*p)++yields the olda[1], which is 2, soyis 2. Thena[1]becomes 3.p - ais 1, becausepmoved once.
All four forms on one array
The next program applies each form in sequence, so you can check your reading against the output.
#include <stdio.h>
int main(void) {
int a[4] = {10, 20, 30, 40};
int *p = a;
int v1 = *p++; /* 10, p now at a[1] */
int v2 = *++p; /* p moves to a[2], value 30 */
int v3 = ++*p; /* a[2] becomes 31, value 31 */
int v4 = (*p)++; /* value 31, a[2] becomes 32 */
printf("%d %d %d %d %d %d\n", v1, v2, v3, v4, a[2], (int)(p - a));
return 0;
}The output is 10 30 31 31 32 2. Note that v3 and v4 are both 31. The prefix form returns the incremented value, and the postfix form returns the value from before the increment.
Where *p++ is useful
The expression *p++ is common in loops that walk through data one element at a time. The classic string copy uses it twice:
#include <stdio.h>
void my_strcpy(char *d, const char *s) {
while ((*d++ = *s++) != '\0') {
;
}
}
int main(void) {
char buf[8];
my_strcpy(buf, "hello");
printf("%s\n", buf);
return 0;
}In each iteration, *s++ reads the current source character and advances s. The assignment stores it through d, and d advances. The assignment's value is the character just copied, so the loop ends after copying '\0'. It prints hello.
Gotchas and edge cases
- Stride depends on the type.
p++addssizeof *pbytes. Forchar *that is 1. Forint *it is typically 4. Only(*p)++changes a value by exactly 1. - An array name cannot be incremented. If
ais an array,a++does not compile, becauseais not a modifiable lvalue.*a++fails for that reason, and*p++works becausepis a variable. Inside a function, a parameter declaredint a[]is really a pointer, soa++is legal there. constblocks only one of the forms. Withconst int *p,(*p)++and++*pare compile errors because the data is read-only.*p++is fine becausepitself can move. Withint *const p, the reverse holds.- Going past the end. After the last
*p++in a loop,pmay point one past the array. Forming that pointer is legal, but dereferencing it is undefined behavior. p++versusp + 1. Both compute the next address, but onlyp++changesp.
Exercises
Exercise
Given int a[3] = {5, 6, 7}; int *p = a; int s = *p++; s += *++p;, what are s and p - a?
Show answer
*p++ yields 5 and leaves p at a[1], so s is 5. *++p moves p to a[2] first, then yields 7, so s becomes 12. The final p - a is 2.
Exercise
Let s point to the string "abc" (four bytes including the terminator). After the loop while (*s++) ; finishes, how far is s from the start of the string?
Show answer
The loop tests each character, then advances s. It tests 'a', 'b', 'c', and finally '\0'. The test of '\0' is false, but s still advances once after reading it. So s ends 4 bytes past the start, one past the terminator.
Exercise
With int a[2] = {4, 9}; int *p = a;, what do (*p)++ and *p++ each do to a[0] and p? Which one is a compile error if p is declared const int *p?
Show answer
(*p)++ makes a[0] equal to 5 and leaves p unchanged. *p++ leaves a[0] as 4 and moves p to a[1]. With const int *p, (*p)++ is the compile error because it writes through a pointer to const data.