Interchanging values of two variables by xor operator using references or pointers

前端 未结 2 506
一向
一向 2020-12-22 06:49

I have two integer variables i and j and I want to make a function which takes these two variables as its argument and interchanges their contents using xor operator. Now if

2条回答
  •  天涯浪人
    2020-12-22 07:30

    As others have noted, this is a pretty silly optimization (if you can call it that). The problem is the chained use of in-place operators. Broken it into separable statements, it works.

    x^=y;  // values are X^Y, Y
    y^=x;  // values are X^Y, X
    x^=y;  // values are Y, X
    

    Like the others, I would encourage you not to riddle your code with such clarity-killing cleverness unless you have a demonstrable need established by profiling and a demonstrable speedup for doing your bit twiddling hack. (cool site)

提交回复
热议问题