C to the MIPS problem

So, I worked on this for a few days and I managed to get through it all, except one part got me sick.

int mystery(int a0)
{
    if (a0 == 0)
    {
        return 0;
    }
    else
    {
        return mystery(a0 - 1) + a0;
    }
}

      

I have this recursive function and I have MIPS code. The C code works, but I have a problem somewhere in my MIPS code that makes it wrong without inserting 2.

.text

main:

li $a0, 2
jal mystery
move $a0, $v0
jal putDec
li $a0, '\n'
li $v0, 11
syscall

li $a0, 3
jal mystery
move $a0, $v0
jal putDec
li $a0, '\n'
li $v0, 11
syscall

li  $v0, 10     
syscall

putDec: 
    li $v0, 1
    syscall 
    jr  $ra     

mystery: 
 bne $0, $a0, recur 
 li $v0, 0      
 jr $ra             

  recur: 
sub $sp, $sp, 8     
sw $ra, 4($sp)  
sub $a0, $a0, 1
jal mystery         
sw $v0, 0($sp)  
jal mystery         
lw $t0, 0($sp)  
addu $v0, $v0, $t0  
addu $v0, $v0, 1    
add $a0, $a0, 1     
lw $ra, 4($sp)  
add $sp, $sp, 8     
jr $ra      

      

Anything about the "riddle" of the label is fine where there is formality to actually enter arguments and print after. The problem I'm running into is getting values ​​above 3 to print out the correct numbers. Help would be greatly appreciated if someone could see where I am doing my mistake. Thanks you

+3


source to share


3 answers


When after a lot of work and tracking the code one step at a time, I think I finally got it, I had to change it a bit, but in fact it seems to me easier now. Here is the code in case you want to review it again if you see an issue that could occur with any specific values ​​that I have not tested. Thanks for the help.

New recursive mystery function:



mystery: 
 bne $0, $a0, recur     
 li $v0, 0      
 jr $ra             

 recur: 
  sub $sp, $sp, 8   
  sw $ra, 4($sp)    
  sw $a0, 0($sp)
  sub $a0, $a0, 1   
  jal mystery       
  lw $t0, 0($sp)    #
  addu $v0, $v0, $t0    
  lw $ra, 4($sp)    
  add $sp, $sp, 8   
  jr $ra        

      

Thanks again.:)

0


source


Try to take a step back and compare the structure of your C code and assembly without worrying about the details.

There is a conditional expression in C code that leads to either the base case (which just returns a value) or the recursive case. The recursive case performs subtraction, recursive invocation, mystery

and addition.



Now let's look at the assembly version: this too has a conditional expression leading either to the base case or to the recursive case. But look at the structure of the recursive case: there are two recursive calls in mystery

there! This is a strong hint that he is unlikely to do the same ...

+3


source


you should return ASCII character, change "li $ v0, 1" in putDec to "li $ v0, 11" (this was not an error)

0


source







All Articles