Sub topic 7
Precedence Traps: `*p++`, `(*p)++`, and `*++p`
Assume you know basic C syntax, arrays, functions, and pointer declaration. You should also know that an array element has a value and an address, and that a pointer can store that address.
Pointer expressions become difficult when dereference * appears with increment operators. The parentheses matter because they determine whether C increments the pointer or the value at the pointed-to location.
The three expressions
Postfix increment has higher precedence than unary dereference. Therefore:
*p++means*(p++).(*p)++means increment the value pointed to byp.*++pmeans*(++p).
The first and third expressions move the pointer. The second changes the array element.
| Expression | Meaning | Pointer moves? | Pointed-to value changes? |
|---|---|---|---|
| `*p++` | Read `*p`, then increment `p` | Yes | No |
| `(*p)++` | Increment the value at `p` | No | Yes |
| `*++p` | Increment `p`, then read `*p` | Yes | No |
For an int *, incrementing the pointer moves it to the next int, not merely to the next byte.
#include <stdio.h>
int main(void) {
int a[3] = {1, 2, 3};
int *p = a;
int x = *p++;
int y = (*p)++;
int z = *++p;
printf("x=%d y=%d z=%d\n", x, y, z);
printf("a={%d, %d, %d}\n", a[0], a[1], a[2]);
printf("position=%td\n", p - a);
return 0;
}The output is:
x=1 y=2 z=3
a={1, 3, 3}
position=2First, *p++ reads a[0], then moves p to a[1]. Next, (*p)++ changes a[1] from 2 to 3, but leaves p unchanged. Finally, ++p moves p to a[2], and *++p reads 3.
A reliable tracing method
When solving an output question, rewrite each expression with explicit parentheses:
- Rewrite
*p++as*(p++). - Record the old value if the increment is postfix.
- Apply the pointer or value change.
- Evaluate the dereference.
- Track the array and pointer position after the statement.
Undefined behavior traps
Do not combine several modifications of the same scalar object in one unsequenced expression. For example, printf("%d %d\n", *p++, *p++) has problematic evaluation order and should not be used for a portable output prediction. Split such operations into separate statements.
Exercise
If int a[] = {4, 5, 6}; int *p = a;, what are the value of *p++ and the final pointer position relative to a?
Show answer
*p++ evaluates to 4, then p points to a[1], so p - a is 1.