Search This Blog

Sunday, July 5, 2009

C++ combining * and ++ Operators

Rules to remember:
  1. ++ and -- takes precedence over *
  2. -> takes precedence over ++ , --, and *
  3. note the difference between postfix and prefix increment and decrement
The value of p++ is p ( because of postfix ++)
The value of *p++? Compile sees *p++ as *(p++), because ++ takes precedence over *.
So *p++ = *(p++) = *p
What happens to the '++' operator? Yes it has its effect. When the next statement is executed,
p(the pointer) will be incremented.

Let's remember the following 4 more examples:
++*p ? ++*p = ++(*p) => the value is the increment of *p.
*++p? *++p = *(++p) => 1. increment p first 2. then the value is *p after incremented
*p++? *p++ = *(p++) => the value is *p. but notice that p is incremented after the statement.
(*p)++? => the value is *p. but notice that *p is incremented after the statement

++*p and *p++ are common. It is a good idea to be familiar with them.

bonus: *p->q ? *p->q = *(p->q) because -> has higher precedence than *
bonus: --p->u ? --p->u = --(p->u) because pre-increment -- has lower precedent than ->


Reference:
p226, C Programming, A Modern Approach.
p205, C, A Reference Manual



No comments: