0

I found out a neat trick to swap the values of two variables without having to create an auxiliar variable. I'll use javascript to illustrate it, although I'm guessing it's language agnostic.


let a = 1;
let b = 2;

a^=b; b^=a; a^=b;

console.log(a); // Prints 2
console.log(b); // Prints 1

Can someone explain how does the swap happen? What does ^= do?

Luis Fernandez
  • 539
  • 1
  • 4
  • 24
  • 1
    It's indeed language agnostic. It's just bitwise arithmetic. [Swapping two variable value without using third variable](https://stackoverflow.com/q/1826159) – VLAZ Apr 22 '22 at 12:21
  • 1
    The second provided question has an appropiate language agnostic answer: https://stackoverflow.com/questions/249423/how-does-xor-variable-swapping-work I do agree with closing the question – Luis Fernandez Apr 22 '22 at 12:30
  • javascript (and others, but not many) can do a swap easier than that `[a,b] = [b,a]` ... so not only do you not need a temporary variable, you only need one statement – Bravo Apr 23 '22 at 01:35

0 Answers0