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 ?
Why?
As you’ve figured out, you need either to pass pointers to the objects, or to use references.
This:
has undefined behavior, since it modifies the same object twice between sequence points (it does this for both
xandy).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:
It’s simple, and it works.