Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Difference between ++*p, *p++ and *++p in C
In C programming, *p represents the value stored at the address a pointer points to. ++ is the increment operator (used in both prefix and postfix forms), and * is the dereference operator. Understanding how these combine requires knowing their precedence and associativity −
- Prefix
++and*have the same precedence and are right-to-left associative. - Postfix
++has higher precedence than both and is left-to-right associative.
The Three Expressions
| Expression | Equivalent To | What Happens |
|---|---|---|
++*p |
++(*p) |
Dereference p, then increment the value. Pointer stays the same. |
*p++ |
*(p++) |
Dereference p (get current value), then increment the pointer. |
*++p |
*(++p) |
Increment the pointer first, then dereference the new location. |
Example
The following program demonstrates all three expressions using an array ?
#include <stdio.h>
int main() {
int arr[] = {20, 30, 40};
int *p = arr;
int q;
// ++*p : increment the VALUE at p (20 becomes 21)
// pointer still points to arr[0]
q = ++*p;
printf("arr[0] = %d, arr[1] = %d, *p = %d, q = %d<br>",
arr[0], arr[1], *p, q);
// *p++ : return VALUE at p (21), then move pointer to arr[1]
q = *p++;
printf("arr[0] = %d, arr[1] = %d, *p = %d, q = %d<br>",
arr[0], arr[1], *p, q);
// *++p : move pointer to arr[2] first, then return VALUE (40)
q = *++p;
printf("arr[0] = %d, arr[1] = %d, *p = %d, q = %d<br>",
arr[0], arr[1], *p, q);
return 0;
}
The output of the above code is ?
arr[0] = 21, arr[1] = 30, *p = 21, q = 21 arr[0] = 21, arr[1] = 30, *p = 30, q = 21 arr[0] = 21, arr[1] = 30, *p = 40, q = 40
Step-by-Step Walkthrough
Step 1: q = ++*p − p points to arr[0] (value 20). Dereference gives 20, increment makes it 21. arr[0] is now 21. q = 21. Pointer still at arr[0].
Step 2: q = *p++ − p still points to arr[0] (value 21). Dereference gives 21, so q = 21. Then pointer moves to arr[1]. Now *p = 30.
Step 3: q = *++p − Pointer moves from arr[1] to arr[2] first. Then dereference gives 40. q = 40.
Conclusion
++*p increments the value the pointer points to. *p++ returns the current value and then moves the pointer forward. *++p moves the pointer forward first and then returns the value at the new location. The key is understanding that postfix ++ binds tighter than *, while prefix ++ and * share the same precedence with right-to-left associativity.
