I am trying to reverse a string input by the user and reverse the string whenever * is hit. For example, if i put abc and hit * i should get abc**cba back. There're 2 functions used it this recursive function which are echo (obtain the input key) and putchar (display the input key). For some reason, my code doesn't give me the * but a weird symbol instead when being echoed back while all of the other keys are fine. Can someone give me a suggestion? Here is my code. Thank you.

recursive:
addi $sp, $sp, -12
sw $ra, 4($sp)
sw $t0, 8($sp)

jal echo
addi $t0, $0, 0x2a
sb $v0, 0($sp)
   # lw $a0, 0($sp)
bne $t0, $v0, recursive

jal putchar
lbu $a0, 12($sp)

lw $ra, 4($sp)
lw $t0, 8($sp)
addi $sp, $sp, 12 

jr  $ra     # Return 

Here is the C program I am trying to translate from

void recursive()
{ char c;
c = echo();
if (c!="*") recursive();
putchar(c);
}

OK, I see a few things you didn't mention, such as a) the particular emulator you are using, and b) whether you are running in realistic mode, with load and branch delays. I also see a major flaw in your algorithm.

As it is now, you are stacking the original return address (and the value of $t0, which is unusual - the normal MIPS calling convention assumes that the temporary registers aren't preserved in calls). You then call your echo function, which has the effect of leaving the return address of line 7 above (or 8, if you have delayed branches on) in $ra. You then do a test that branches to the top of the recursive function if the character value is not an asterisk. The problem with doing this at this juncture is that you are then stacking the return value of the call to echo, not the return to the branch location. You would need to use a branch on equals and jump past a jump and link to the recursive call to get the desired effect.

(The trick you are trying to use does work, but only with tail recursive functions, where you are basically reusing the existing stack.)

So why does it seem to work, except for the asterisk? Well, to be honest, I'm puzzled by that, and I haven't time to work it all out in detail.

This article has been dead for over six months. Start a new discussion instead.