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 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.
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)