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

后端 未结 5 1639
天命终不由人
天命终不由人 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:59

    Chapter 5 Expressions

    Point 4:

    Except where noted, the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified. Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored. The requirements of this paragraph shall be met for each allowable ordering of the subexpressions of a full expression; otherwise the behavior is undefined.

    [ Example:
      i = v[i ++];           / / the behavior is undefined
      i = 7 , i++ , i ++;    / / i becomes 9
      i = ++ i + 1;          / / the behavior is undefined 
      i = i + 1;             / / the value of i is incremented
    —end example ]
    

    As a result this is undefined behavior:

    int i;
    int *p = &i;
    int *q = &i;
    *p = ++(*q);   // Bad Line
    

    In 'Bad Line' the scalar object 'i' is update more than once during the evaluation of the expression. Just because the object 'i' is accessed indirectly does not change the rule.

提交回复
热议问题