1

As a part of a fairly complex function, I wrote this bit of code:

if( (((int)*(pointer-11 ....  )   //It is too long and complex
{
    *(pointer++)=*(pointer-12)+1;
}
else
{
    *(pointer++)=*(pointer-12);
}

The if part works well, but the else parts works like:

*(pointer++)=*(pointer-11);

When I put the incrementing code separate from the actual line ,

if( .... )
{
    *(pointer)=*(pointer-12)+1;
}
else
{
    *(pointer)=*(pointer-12);
}
pointer++;

It works perfectly. But code on top should work too, right? Any thoughts?

5
  • 5
    You wouldn't know if the pointer++ or the pointer-12 part is evaluated first. It's up to the compiler. Commented May 9, 2020 at 14:45
  • 3
    This code has undefined behavior. If you modify pointer on the left hand side of an assignment, then you cannot reference it on the right hand side (and vice versa). If you do, the result will be undefined and could vary from compiler to compiler, or with different optimization levels, or even from one release to another. Just don't do it. Commented May 9, 2020 at 15:07
  • Also, you can write *(pointer-12) as pointer[-12], and *(pointer) as just *pointer, or as pointer[0]. Commented May 9, 2020 at 15:09
  • Oh So it is related to the compiler.. right? Commented May 9, 2020 at 15:48
  • So I should separate it as 2 statements..? Commented May 9, 2020 at 15:49

1 Answer 1

2

*(pointer++)=*(pointer-12); is undefined behavior. There is no sequence point here, so you don't know if the left or right part of the = will get evaluated first.

Since it's undefined behavior, the compiler might do anything, but these are pretty sensible interpretations of it:

// Left gets evaluated first    
*(pointer)=*((pointer+1)-12);
pointer++;

// Right gets evaluated first
*(pointer)=*(pointer-12);
pointer++;

Note that this has nothing to do with pointers. The expression x++ <op> x causes undefined behavior irregardless of what type x has and what operator <op> is. (That's maybe not 100% true, but you better avoid these expressions anyway)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.