问题
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