Cluv
Cluv

Reputation: 37

Pointers: Difference between *p++ as lvalue and rvalue

So I am confused about one thing about pointers. Lets look at this:

*p++

I know that operator ++ is "bigger"(sorry idk how else to say, i am not native english speaker) than operator *. So that means that *p++ is in fact percieved as *(p++). So what confuses me is differenet outcome when *p++ is used as lvalue and rvalue. For example:

If I want to sum all elements of array this will work fine(used as rvalue):

sum += *p++;

My question here is why this it first happens *p and then p++, when ++ is bigger then *. Why it wouldnt first happen p++ and then *p.

But if i use it as lvalue, it works as I expected to do. For example:

*p++ = round(*p * 100) / 100;

It first happens p++ and then this new number is given to *p.

Why these 2 thing are different, when it is used as rvalue and lvalue, i mean i am confused why this example with sum.

Thanks :)

Upvotes: 0

Views: 77

Answers (2)

John Bode
John Bode

Reputation: 123448

Postfix ++ has higher precedence than unary *, so *p++ is parsed as *(p++). In other words, you are applying * to the result of p++.

The result of p++ is the current value of p. As a side effect, p is incremented by 1. With pointers, this means that p is updated to point to the next object in a sequence. IOW, if you have this situation:

+---+---+---+---+
|   |   |   |   |
+---+---+---+---+
  ^
  +---+
      |
    +---+
 p: |   |
    +---+

then after executing p++ (or p = p + 1), you will have this:

+---+---+---+---+
|   |   |   |   |
+---+---+---+---+
      ^ 
      |
      |
    +---+
 p: |   |
    +---+

This is true regardless of the type of the objects in the sequence, so the address value stored in p may be incremented by more than 1.

Upvotes: 1

Eric Postpischil
Eric Postpischil

Reputation: 222437

The precedence of operators tells us how to structure an expression. Parentheses can be used to show the structure, so sum += *p++ is sum += (*(p++)).

When evaluating the expression, we use the meaning of each operator, also called its semantics.

  • The meaning of postfix ++, as in p++, is “Do two things, separately: Get the current value of the operand and use that as the value of this expression. And increment the operand.” Thus, with p++, the value of the expression is p, and separately p is incremented. The increment does not affect the value of the expression; it is p before the increment occurs.
  • The meaning of unary * is “Dereference the pointer.” So the result of *(p++) is *p, which is the object p points to (without the increment).

Upvotes: 0

Related Questions