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
Precedence of postfix ++ and prefix ++ in C/C++
In C programming, understanding operator precedence between prefix increment (++var), postfix increment (var++), and dereference operator (*) is crucial for writing correct pointer code. The precedence order is: postfix operators have highest precedence, followed by prefix operators, then dereference.
Syntax
++*ptr // Equivalent to ++(*ptr) - increment value at ptr *ptr++ // Equivalent to *(ptr++) - dereference then increment pointer (*ptr)++ // Increment value at ptr (postfix)
Precedence Rules
- Postfix ++/-- has highest precedence
- Prefix ++/-- and dereference * have same precedence (right-to-left associativity)
- When ptr is a pointer:
*ptr++means*(ptr++)and++*ptrmeans++(*ptr)
Example 1: Prefix Increment with Dereference
This example shows ++*ptr which increments the value pointed to by ptr −
#include <stdio.h>
int main() {
char arr[] = "Hello World";
char *ptr = arr;
printf("Before: *ptr = '%c'\n", *ptr);
++*ptr; // Equivalent to ++(*ptr)
printf("After ++*ptr: '%c'\n", *ptr);
return 0;
}
Before: *ptr = 'H' After ++*ptr: 'I'
Here ++*ptr first dereferences ptr to get 'H', then increments it to 'I'. The pointer location remains unchanged.
Example 2: Postfix Increment with Dereference
This example demonstrates *ptr++ which dereferences the current pointer value, then moves the pointer −
#include <stdio.h>
int main() {
char arr[] = "Hello World";
char *ptr = arr;
printf("Before: *ptr = '%c'\n", *ptr);
char value = *ptr++; // Equivalent to *(ptr++)
printf("Retrieved: '%c'\n", value);
printf("After *ptr++: *ptr = '%c'\n", *ptr);
return 0;
}
Before: *ptr = 'H' Retrieved: 'H' After *ptr++: *ptr = 'e'
Here *ptr++ returns 'H' (current value), then increments the pointer to point to 'e'. The original value at arr[0] remains 'H'.
Comparison Table
| Expression | Equivalent | Operation | Result |
|---|---|---|---|
++*ptr |
++(*ptr) |
Increment value at ptr | Value changed, pointer unchanged |
*ptr++ |
*(ptr++) |
Get value, then move pointer | Pointer advanced, original value unchanged |
(*ptr)++ |
(*ptr)++ |
Postfix increment of value | Value changed after use |
Conclusion
Remember that postfix operators have higher precedence than prefix and dereference operators. Use parentheses for clarity when combining these operators to avoid confusion and ensure correct program behavior.
