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

后端 未结 5 1637
天命终不由人
天命终不由人 2021-02-13 22:02

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;
          


        
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-13 22:42

    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.

提交回复
热议问题