Tuesday, September 12, 2017

Difference between *p++, *++p and ++*p

One of the most common question is which version of *p++, *++p or *p++ to use while programming.

There is no right answer and the answer varies from the usage point of view. Understanding the output of each form would help you in deciding which one should be used.

There are two simple rules to remember related to postfix, prefix and de-reference operator.

1. Precedence of postfix is higher than both prefix and de-reference operator. Associativity of postfix operator is left to right.

2. Precedence of prefix and de-reference operator is same. Associativity is right to left.

Let's try to understand the results based on these rules by below examples -

int a[] = {5, 10};
int *p = a;

*p++
Result - 10
The precedence of p++ is higher so pointer is incremented first and then de-referenced.

*++p
Result - 10
The associativity is right to left so pointer is incremented first and then de-referenced.

++*p
Result -6
The associativity is right to left so pointer is de-referenced first then incremented.

Please leave your comments with suggestions/feedback.