C++ – Is this “*ptr++ = *ptr + a” undefined behavior


Well, I'm not really in serious need of this answer, I am just inquisitive.

Expressions like *ptr++ = a are perfectly valid since we are operating on two objects ptr and *ptr but if i write *ptr++ = *ptr + a is it still valid ?

For example consider the following snippet:

int main(void){
   int a[] = {5,7,8,9,2};

   int* p =a;

   *p++ = 76; /*altering the first element */
   *p++ = *p + 32; /*altering the second element */    

   p = a;
   int i;
   for(i = 0;i<5; i++)
      printf("%d ",*p++);

   return 0;

I think that there is nothing to worry about with the expression *p++ = *p + 32; but I am unsure about the sequence points involved.

Best Solution

The result of *ptr++ = *ptr + a is undefined. The equals sign is not a sequence point, so using the value of ptr again in that statement results in undefined behavior. Just consider the result if ptr is incremented before the RHS expression is evaluated, and compare it with the case where ptr is incremented after the RHS expression.

Note: this is not to say that the result of the expression will be from either of those two scenarios. Undefined is undefined.

Basically, you can only count on two things: that the post-increment is evaluated some time between the last sequence point and the next one, and that the expression ptr++ returns the value of ptr before it is incremented. So *ptr++ = a is fine because you can count on the result of ptr++.