0
main:

    jal function1

  #Exit Program
    li $v0, 10
    syscall

function1:

    li $s0, 0
    jal function2

    jr $ra 

function2:

    jal external_function
    beq $s0, 5, function2_end

    #Run loop 5 times
    addi $s0, $s0, 1

function2_end:
    jr $ra

external_function:
    #Does random operation
    jr $ra

So this is just an example of a problem of what I am having with MIPS. I get stuck in an infinite loop because function2_end will keep on jumping to the external_function.

Is there a way to have function2_end jump back to function1, so it can exit the loop?

user3718441
  • 85
  • 1
  • 3
  • 11
  • Functions need `$ra` to return to the correct place, but calling another function using `jal` will overwrite it with the new value. You need to save it on the stack in non-leaf functions. – Jester Oct 12 '14 at 21:19

1 Answers1

1

jal saves the value of $ra, overwriting any previous value. What you want to do is save $ra to the stack when necessary, and then pop it when you want it back.

qwr
  • 9,525
  • 5
  • 58
  • 102