Swapping values of two variables

MRAB google at mrabarnett.plus.com
Fri Jan 30 15:47:37 CET 2009

Grant Edwards wrote:
 > On 2009-01-30, MRAB <google at mrabarnett.plus.com> wrote:
 >>> What is the minimum amount of extra memory required to exchange two
 >>> 32-bit quantities? What would be the pseudocode that achieves this
 >>> minimum?
 >> x ^= y
 >> y ^= x
 >> x ^= y
 >> This is really only of use when working in assembly language.
 > And rarely then. ;)
 > [Readability counts everywhere.]
It can be useful if you want to swap the contents of 2 registers in ARM
assembly language:

EOR r0,r0,r1
EOR r1,r0,r1
EOR r0,r0,r1

The quickest alternative is to use MOV:

MOV r2,r0
MOV r0,r1
MOV r1,r2

The same number of instructions, program bytes, and clock cycles, but
requiring an additional register!

More information about the Python-list mailing list