DEV Community

Discussion on: How can you swap two variables without using a third?

Collapse
 
yaser profile image
Yaser Al-Najjar • Edited

Only two options, either using memory or CPU

  1. Memory = third variable
temp = x
x = y
y = temp
  1. CPU = Swap algorithms

like XOR swap (bullet-proof solution)

x ^= y
y ^= x
x ^= y

Or addition & subtraction (which is not bullet-proof when dealing with a 32-bit register that would need extra care with overflow)

x += y
y = x - y
x -= y
Collapse
 
dean profile image
dean

XOR swap is NOT bullet proof, you need to check if x == y first. If x == y, then the function sets both values to zero.

Collapse
 
johnfound profile image
johnfound • Edited

No, it will not. Let set x=5, y=5.

x = x xor y = 5 xor 5 = 0
y = y xor x = 5 xor 0 = 5
x = x xor y = 0 xor 5 = 5

It is a nop actually, but still correct.