Are there sequence points in the expression a^=b^=a^=b, or is it undefined?

前端 未结 4 1552
[愿得一人]
[愿得一人] 2020-12-11 15:15

The allegedly \"clever\" (but actually inefficient) way of swapping two integer variables, instead of using temporary storage, often involves this line:

int         


        
4条回答
  •  轮回少年
    2020-12-11 16:05

    a ^= b ^= a ^= b; /*Here*/
    

    It is undefined behavior.

    You are modifying an object (a) more than once between two sequence points.

    (C99, 6.5p2) "Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression.

    Simple assignments as well as compound assignments don't introduce a sequence point. Here there is a sequence point before the expression statement expression and after the expression statement.

    Sequence points are listed in Annex C (informative) of the c99 and c11 Standard.

提交回复
热议问题