Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Mips swapping without temp variable

  1. Mar 18, 2013 #1
    so i have swap.s
    Code (Text):
        la  $a0,n1
        la  $a1,n2
        jal swap
        li  $v0,1   # print n1 and n2; should be 27 and 14
        lw  $a0,n1
        li  $v0,11
        li  $a0,' '
        li  $v0,1
        lw  $a0,n2
        li  $v0,11
        li  $a0,'\n'
        li  $v0,10  # exit



    n1: .word   14
    n2: .word   27

    my goal is to:
    Modify swap.s to translate the following procedure directly to MIPS
    assembly language. The temp variable, like all local variables in C
    (when not optimized), is stored on the stack. In other words you
    cannot use $t0 to hold temp, though you may need it briefly. Hint: you
    will need to use 6 lw/sw instructions.
    This exercise is slightly contrived, and could be easier if we let you
    optimize and use $t0 to hold the temp variable, part of the point of this
    exercise is to see what kind of difference optimization can make.
    Code (Text):
    void swap (int *px, int *py) {
    int temp;
    temp = *px;
    *px = *py;
    *py = temp;

    i am confused on jal and jr's though...

    for swap could I just do:
    Code (Text):
    xor $a0 $a0 $a1
        xor $a1 $a0 $a1
        xor $a0 $a0 $a1
        jr $ra
    or do i need to save to the stack and such?
  2. jcsd
  3. Mar 18, 2013 #2


    User Avatar
    Science Advisor

    Hey jiggleswiggly and welcome to the forums.

    That piece of XOR code is actually a real swap that works without needing a temporary variable.

    If you wanted to prove it then use the properties of XOR and note that A XOR A = 0 and 0 XOR B = B for any B and A.
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook