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

前端 未结 4 1551
[愿得一人]
[愿得一人] 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 15:51

    There are no sequence points in that expression, so it produces undefined behavior.

    You could fix it trivially and retain most of the succinctness by using the comma operator, which does introduce sequence points:

    a ^= b, b ^= a, a ^= b;
    

提交回复
热议问题