Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning to postfix-incremented pointers

I have read that postfix increment and decrement operators return rvalues of the operands. Assuming that is true, how are codes like this possible?:

int arr[5]{};
int *p = arr;
for (int i = 0; i != 5; ++i)
    *p++ = i;

My thought procees is

  1. According to operator precendence, *p will get evaluated first.
  2. Then postfix increment will increment the value and return a copy of the object as an rvalue.
  3. Then I get confused because rvalues should not be on the left hand side of assignment operator... So my question basically is : how is *p++ = i; possible?
like image 474
Zylon D. Lite Avatar asked Mar 13 '26 06:03

Zylon D. Lite


2 Answers

According to operator precendence, *p will get evaluated first.

Wrong.

Here:

*p++

the increment will be evaluated first, and not the *p.

This gives an rvalue (the pointer's value), and after the dereference, this becomes an lvalue which you are able to assign to i.

You could rewrite your for loop to this:

for (int i = 0; i != 5; ++i) {
    std::cout << *p << std::endl;
    *p++ = i;
    std::cout << *p << std::endl;
}

to get a better view.

like image 70
gsamaras Avatar answered Mar 14 '26 18:03

gsamaras


According to operator precendence, *p will get evaluated first.

You are mistaken. According to the documentation, the increment will be evaluated first. This will yield an rvalue (i.e. the value of the pointer before it got incremented), which then, after it get's dereferenced, is an lvalue you can assign to.

like image 41
Jodocus Avatar answered Mar 14 '26 20:03

Jodocus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!