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
*p will get evaluated first.*p++ = i; possible?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.
According to operator precendence,
*pwill 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With