Swapping values of two variables

Grant Edwards invalid at invalid
Fri Jan 30 18:05:11 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!

Yea, I guess the ARM's SWP instruction only works on
register<->memory.  That said, I don't remember ever needing to
swap the contents of two register when working in ARM assembly
language (yes I have done some).  I always just use the value
in the register where it is.  Swap with top of stack (for which
the SWP instruction works) can be useful for implementing some
sorts of stack-based VMs, but register-register swap just
doesn't seem to be something one needs to do (which probably
explains why there's no instruction to do it).

Given the choice between the cryptic version that doesn't
require a third register, and the obvious version that uses a
third register, I'll usually choose the latter.  There aren't
that many people left who'll recognize what the triple-xor
sequence is doing -- so if I ever would use it, I'd probably
make it a macro.

-- 
Grant Edwards                   grante             Yow! This ASEXUAL PIG
                                  at               really BOILS my BLOOD
                               visi.com            ... He's so ... so
                                                   ... URGENT!!



More information about the Python-list mailing list