Home > Software engineering >  Printing list in MIPS recursion
Printing list in MIPS recursion

Time:03-21

Currently, I am working with MIPS, and I was wondering what modifications should I make to following code(recursive function to print list):

printList:
   addi $sp, $sp, -8
   sw $ra, 0($sp)
   beqz $a0, endRec
   lw $t0, 0($a0)
   sw $t0, 4($sp)
   lw $a0, 4($a0)
   jal printList
   lw $a0, 4($sp)
   li $v0, 1
   syscall
   la $a0, str
   li $v0, 4
   syscall
endRec:
   lw $ra, 0($sp)
   addi $sp, $sp, 8
   jr $ra

such that it prints list in "normal" order(for example if I am adding elements on the end, 1 2 3, I want it to print it like that and not like 3 2 1). NOTE: str is blanco defined in data segment. I also know that I could do reverse list and then call that function, but is there easier way?

CodePudding user response:

Though you're working in MIPS, this is not really a MIPS problem, it is a general problem of recursion.

In recursion, let's say we have:

recursiveFunction (...) {
    if condition then exit

    // do some work #1

    recursiveFunction (...);

    // do some other work #2
}

The work that is done in the section tagged #1 will happen before the recursion, e.g. on the recursive descent — in some sense this happens forwards.

The work that is done in the section tagged #2 will happen after the recursion, e.g. on the unwinding of the recursion — in some sense this happens backwards.

If you put the printing in section #2, the list will come out backwards.  If you put the printing in section #1, the list will come out forwards.

  • Related