decoding * and inc/dec operator combos like *++p , *p-- ,etc

This tip submitted by kishore on 2013-05-12 14:14:58. It has been viewed 939 times.
Rating of 0.0 with 0 votes

Consider a pointer p(for simplicity let it point to an integer variable).
You would be knowing know that *++p is not the same as ++*p.
I can be broken as ++p and dereferencing of the updated value of p.
You might use these constructs with heavy usage of parenthesis while simple non parenthesized versions will do.

OK,here is how you decrypt it.

1.Start reading from left to right.

As both the * and the inc/dec operators (++/--) are unary the variable should immediately follow the operators(with the exception of postfix inc/dec).

2.If the variable immediately follows the operator perform that operation then apply the next operator (after the variable) on the variable only.
Ex: *p++ ---> *p and then p+1.The next reference on p points to the next integer address.

3.If the operator is followed by another operator,break down the statement as two blocks first the inner block and the outer operator (the first operator in our case) on the result.
Ex: ++*p ---> ++(*p)
*--p ---> *(p-1)
Note that the third step can apply to multiple operators like *++*q--
where q is a pointer to a pointer.

To break down the above
*{++[*q--]} should make the idea clear.

The above is not valid in all cases.

Now you know how to break this down do not over exploit parenthesis like this:
*(++p) , --(*p) --> the non parenthesized version does the same.

But for some you need to use parenthesis, like:
dereferencing (*) the post incremented value of pointer (p++) i.e *(p++). Here without parenthesis this reads as post incrementing the value referenced by p (*p) which is not what we intended.

Happy coding!

More tips

Help your fellow programmers! Add a tip!