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

白昼怎懂夜的黑 提交于 2019-12-18 09:41:59

问题


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 I make the function to take arguments by value i.e void swap (int x , int y);(with function body same as for the function swap below) then the values are being swapped nicely within the function. But as what I want is the swapping of the values of the variables in the calling function I used passing arguments by reference (and by pointers as well) :

void swap ( int& x , int& y )
{
    x^=y^=x^=y;
    cout << x<< " " << y << endl ;
}

int main ()
{
    int i (1), j (2) ;
    swap ( i, j ) ;
    cout << i << " " << j << endl ;
}

but neither case showed the correct result !

Why is the swap function not swapping the values on passing arguments by reference or pointers ?


回答1:


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.

Why?

As you've figured out, you need either to pass pointers to the objects, or to use references.

This:

x^=y^=x^=y;

has undefined behavior, since it modifies the same object twice between sequence points (it does this for both x and y).

The xor trick fails if both objects are the same object; the first xor zeros the object.

If you want to swap two objects, just use a temporary:

int temp = x;
x = y;
y = temp;

It's simple, and it works.




回答2:


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)



来源:https://stackoverflow.com/questions/10971895/interchanging-values-of-two-variables-by-xor-operator-using-references-or-pointe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!