Search code examples
cc99operator-precedencesequence-points

Is "*p = ++(*q)" undefined when p and q point to the same object?


after reading about sequence points, I learned that i = ++i is undefined.

So how about this code:

int i;
int *p = &i;
int *q = &i;
 *p = ++(*q);           // that should also be undefined right?

Let's say if initialization of p and q depends on some (complicated) condition. And they may be pointing to same object like in above case. What will happen? If it is undefined, what tools can we use to detect?

Edit: If two pointers are not supposed to point to same object, can we use C99 restrict? Is it what 'strict' mean?


Solution

  • Yes, this is undefined behavior -- you have two modifications of an object without a sequence point between them. Unfortunately, checking for this automatically is very hard -- the best I can think of is adding assert(p != q) right before this, which will at least give a clean runtime fault rather than something worse. Checking this at compile time is undecidable in the general case.