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

后端 未结 5 1636
天命终不由人
天命终不由人 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条回答
  •  执笔经年
    2021-02-13 22:54

    That's a good question. The one thing you have highlighted is 'sequence points', to quote from this site

    why you cannot rely on expressions such as: a[i] = i++; because there is no sequence point specified for the assignment, increment or index operators, you don't know when the effect of the increment on i occurs.

    And further more, that expression above is similarly the same, so the behaviour is undefined, as for tools to track that down, is zero, sure there's splint to name one as an example, but it's a C standard, so maybe there's a hidden option in a tool that I have not yet heard of, maybe Gimpel's PC Lint or Riverblade's Visual lint might help you although I'll admit it does not mention anything about tracking down undefined behaviour in this regard.

    Incidentally, GCC's compiler version 4.3.3 has this option -Wsequence-point as part of flagging up warnings..this is on my Slackware 13.0 box...

    It just shows, that code may look ok to the naked eye and will compile just fine, but can cause headaches later on, the best way to do it is to have code review that can spot out things a compiler may not pick up on, that is the best weapon of choice!

提交回复
热议问题