Only two options, either using memory or CPU
temp = x x = y y = temp
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
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.
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.
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Only two options, either using memory or CPU
like XOR swap (bullet-proof solution)
Or addition & subtraction (which is not bullet-proof when dealing with a 32-bit register that would need extra care with overflow)
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.
No, it will not. Let set x=5, y=5.
It is a nop actually, but still correct.