Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would ++*ptr++ be evaluated by compiler if ptr is ptr to first element of a static array?

What is the order of evaluation in ++*ptr++? Does it change when pointers and lvalues are involved in the operation?

If the precedence of a++ is higher than *a or ++a, then why is ++*a++ evaluated as first returning the incremented value then changing the pointer, rather than changing the pointer, then incrementing the value at the location. Refrence for Precedence: https://en.cppreference.com/w/cpp/language/operator_precedence

arr = {9, 99, 999 };
int *ptr = arr;
std::cout << ++*ptr++ << '\t';
std::cout << *ptr;

I expected the output to be 100 100, but the actual output was 10 99.

like image 415
Aditya Chopra Avatar asked Dec 08 '25 09:12

Aditya Chopra


1 Answers

The postfix increment a++ increments the pointer ptr, but returns the copy of ptr before the operation (see difference between prefix/postfix). So it can be rewritten (as noted in Quimby's answer) as ++(*(ptr++)) and goes like:

  1. ptr++ : increments ptr so that it points to 99, but returns another pointer that still points to 9
  2. *ptr++ : dereferences, evaluates to 9
  3. ++*ptr++ : increments the value pointed to by the copied pointer, meaning increments 9 and returns 10

Here the logic behind pre/post increment/decrement is explained well:

Pre-increment and pre-decrement operators increments or decrements the value of the object and returns a reference to the result. Post-increment and post-decrement creates a copy of the object, increments or decrements the value of the object and returns the copy from before the increment or decrement.

From: https://en.cppreference.com/w/cpp/language/operator_incdec

like image 64
Lock-not-gimbal Avatar answered Dec 10 '25 22:12

Lock-not-gimbal



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!