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 ++*ptr means ++(*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.

Updated on: 2026-03-15T10:13:42+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements