4

I apologize if this is asked in a strange way, this is my first time asking a question here. In swapping two variables, I came across this line after a google search:

x = x^i^(i = x);

In context, I have two ints, i and x, and this line swaps their values. I've been trying to understand the logic behind this and I can't quite get it. The closest I've come is realizing that, on a mathematical scale, they're equal. Throwing it into an online calculator shows that both sides equal x. The closest thing I can think of is:

(i = x) is false, so it's a zero?

so i^0 is 1

so x = x^1

But even with this, I still can't understand how this swaps the two numbers.

1 Answers1

6

The confusion probably comes from the operator. The tiny hat ^ (circumflex) is an XOR, not an exponential.

The statement i = x within the parentheses assigns the value of x to i. At the same time, that statement returns that values x for further use. So after assigning the value to i, the remainder of the formular is x^i^x, where x XOR x eliminates itself, so that x = i remains.

However: I don't see why anyone would want to use that, if you could use a more comprehensible way of just using a temporary variable:

int tmp = i;
i = x;
x = tmp;
  • 1
    For more information on the XOR operator for OP, check this other SO question [here](https://stackoverflow.com/questions/1991380/what-does-the-operator-do-in-java). – Nexevis Feb 03 '20 at 18:10